What's wrong with the jQuery live method?

Solution 1:

See some of the explanations here:

http://www.ultimatewebtips.com/why-jquery-live-is-a-bad-option-to-use/ (Site appears to be down)

Quote:

  1. You can’t use .live() for reusable widgets.

  2. .stopPropagation() doesn’t work with live.

  3. .live() is slower.

  4. .live() is not chainable.

Further beauty of .on() is that it streamlines all events quite well: http://api.jquery.com/on/

D'uh you know about the api link and see how .on() works :)

Quote:

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

Solution 2:

live() is inefficient for two reasons:

  • In the construct $('selector').live(), jQuery first has to select all elements. However, when calling live(), it only needs the selector of the jQuery object (stored in .selector) and doesn't actually use any of the selected elements. Therefore, it is somewhat wasteful to first select all matching elements and then not using them. on() and delegate() take the target selector as a parameter which means that no target elements are selected beforehand and the testing occurs only when the event is triggered.
  • live() by default is bound at the document level, thus all events need to bubble up through the whole DOM. You can narrow it down by specifying a context with $(selector, context).live(), but it's better to use on() or delegate() for this.

When writing new code, it is strongly recommended to use the latest and greatest on() instead of delegate() and the deprecated live(). However, I don't think support for live() will be dropped anytime soon (if ever), as so many scripts rely on it. Also, there's no real disadvantage of using live() over on(), as in the jQuery source itself live() is defined as:

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
}

Solution 3:

There are two main issues with the live method:

  1. It attaches all event handlers at the document level, so any event that bubbles up to the document has to be matched against the event types and selectors for all live events. If you have a lot of events, the page will be sluggish. You should use delegate or on to limit the scope of where you check the events.

  2. The usage of the method is not typical for how selectors is used with other methods in the library. You can only use it on jQuery objects that are created using a selector. The delegate and on methods makes this natural as you supply the selector to the method.