I get asked very often when to use the jQuery bind() and live() event methods. By definition, bind() will bind a handler to one or more events for each matched element currently exists, at the time the call is made; whereas live() uses event delegation to bind a handler to an event for all current and future matched elements.
live() works by attaching your event handler to the document, not just to the element. For example, when you click on a button, that button might exist in a
<p>, in a
<div>, in a
<body> element; so in effect, you're actually clicking on all of those elements at the same time. It then looks back up the line of elements targeted by the event and checks to see if any of them match your query.
Code examples are always helpful to understand the difference. Here are two sample code which are almost the same, the only difference is the first one uses bind() and the second one uses live().
You will see the following response in the browser. In the code above, when the user clicks on the paragraph, a new <p> paragraph will be created beneath it. Clicking on the newly created paragraph will not replicate the functionality.
Now, we will try live() method. Just replace .bind with .live.
You will see the following response in the browser. In the code above, the user can now click on any of the paragraph, and a new <p> paragraph will be created beneath it. The only difference is live() method is used here.
With live() method, it means that you don't have to continue reapplying events to new elements, since they'll be implicitly added when the event happens. More importantly, it means that your code can be much lighter and more maintainable. You can use this technique for animation, games to make your application more visually appealing.
bind() will only apply to the items you currently have selected in your jQuery object.
live() will apply to all current matching elements, as well as any you might add in the future. If you have controls that aren’t rendered dynamically, use bind(). If you have controls that are rendered dynamically, use live().
Caveats (to be aware)
.live() technique is useful, but due to its special approach cannot be simply substituted for
.bind() in all cases. Specific differences include:
- DOM traversal methods are not supported for finding elements to send to
.live(). Rather, the
.live()method should always be called directly after a selector, as in the example above.
- To stop further handlers from executing after one bound using
.live(), the handler must return
.stopPropagation()will not accomplish this.
- As of jQuery 1.4 the
- As of jQuery 1.4.1 even
blurwork with live (mapping to the more appropriate, bubbling, events
- As of jQuery 1.4.1 the
hoverevent can be specified (mapping to
mouseleave, which, in turn, are mapped to