Using bind() to Write Even Less Code with jQuery

Let's say our client wants us to code something up that dynamically highlights a row when the user moves the cursor in it, and restores the row back to its previous state once the mouse cursor leaves the row.

This can be accomplished easily in jQuery by chaining together the mouseenter() and mouseleave() methods.

$('.row').mouseenter(function() {
}).mouseleave(function() {

Simple, right? This solution may work for the scenario above, but there are two significant issues staring us right in the face.

First, this solution does not scale well. Chaining methods together can create some really compact and fantastic functionality. However, it can also lead to code that is difficult to read and even harder to debug. If our customer comes back to us and wants additional functionality added to each row, we could be setting ourselves up for some problems down the line.

Second, we have the issue of code duplication. In the first example we have two identical calls to toggleClass() which is never a good idea.

Luckily, jQuery provides us with an elegant solution to our problem, the bind() method.

bind() will attach one or more events to a set of elements. The following code will produce the same functionality as the first example.

$('.row').bind('mouseenter mouseleave', function(e) {

bind() also gives us the flexibility of adding additional events to our selector's elements without having to add any more lines of code. All we have to do is add another space-delimited event in the bind() method.

Using bind() is a subtle way to make your code cleaner and simpler without having to do any extra work. In fact, you actually need to do less work to accomplish the same goal. Isn't jQuery great?

Creative Commons License

What do you think?