What's the difference between jQuery .live() and .on()

Solution 1:

It's pretty clear in the docs why you wouldn't want to use live. Also as mentioned by Felix, .on is a more streamline way of attaching events.

Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .live():

  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
  • Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.
  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
  • The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind("click") removes all click handlers attached by any call to .live()!

Solution 2:

One difference that people stumble on when moving from .live() to .on() is that the parameters for .on() are slightly different when binding events to elements added dynamically to the DOM.

Here's an example of the syntax we used to use with the .live() method:

$('button').live('click', doSomething);

function doSomething() {
    // do something
}

Now with .live() being deprecated in jQuery version 1.7 and removed in version 1.9, you should use the .on() method. Here's an equivalent example using the .on() method:

$(document).on('click', 'button', doSomething);

function doSomething() {
    // do something
}

Please note that we're calling .on() against the document rather than the button itself. We specify the selector for the element whose events we're listening to in the second parameter.

In the example above, I'm calling .on() on the document, however you'll get better performance if you use an element closer to your selector. Any ancestor element will work so long as it exists on the page before you call .on().

This is explained here in the documentation but it is quite easy to miss.

Solution 3:

See the official Blog

[..]The new .on() and .off() APIs unify all the ways of attaching events to a document in jQuery — and they’re shorter to type![...]