jQuery 1.7+ .on() vs .live() Review

Sam Deering

I was recently watching a recording of jQuery summit 2011, I think it was Adam Sontag who was suggesting to use new functions called .on() and .off() event handlers instead of .live(). After using .live() quite regularly over the past few years i wanted to see the main differences and consider using the new functions .on() and .off() recently added in jQuery 1.7.

Let’s look at the functions and how they work.

jQuery .live()

Attach an event handler for all elements which match the current selector, now and in the future.

source: http://api.jquery.com/live/

When .live() came to existence a few years ago it was the “dogs balls!”. Finally, we can attach events to elements that are inserted dynamically into the DOM. .live() does a great job in providing this feature. However, as things go, jQuery is continuously evolving and now we’re seeing some new kids on the block. See demo of .live() function.

jquery4u-live-event-diagram

jQuery .on()

Attach an event handler function for one or more events to the selected elements.

source: http://api.jquery.com/on/

jquery4u-on-event-diagram1

jquery4u-on-event-diagram2

This brings us to a few questions.

What is wrong with .live()

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():

  1. jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
  2. Chaining methods is not supported. For example, $(“a”).find(“.offsite, .external”).live( … ); is not valid and does not work as expected.
  3. Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  4. 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.
  5. 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()!

Whats the main differences between .live() and .on() functions?

Functionality: Instead of bubbling up the body and document level it is directly registered against the document.

Usage:
If we look at the 3 main event attachment methods we can see that they are very similar. Noticably the .live() doesn’t have a selector parameter.

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

Performance: I was going to create a jsPerf test but found someone already did the hard work! Here are the results of the performance of .live() and .on(). As you can see, .on() outperforms it’s predecessor .live(), it’s almost 3 or 4 times as fast!

live-vs-on-performance-results

Will .on() work in earlier versions of jQuery?

As far as I know, the .on() function was only included in jQuery 1.7 it won’t work with earlier versions.

.off()

Remove an event handler.

This one is simple, it basically can be used to remove event handlers. A bit like the .unbind() event which removes event handlers previously attached to elements.

What’s the difference between bind() and on()?

If we take a look at the jQuery 1.7 source code we can see that bind() uses on() and unbind() uses off(). So essentially no difference and maintains backwards compatibility for earlier versions of jQuery.

//http://code.jquery.com/jquery-1.7.1.js
//line 3755
    bind: function( types, data, fn ) {
        return this.on( types, null, data, fn );
    },
    unbind: function( types, fn ) {
        return this.off( types, null, fn );
    },

So to sum up, as suggested by the jQuery experts you should start using .on() and .off() instead of .live() for your next project developments.

Update 04/06/2012

As of jQuery 1.7 the .bind() and .live() functions are in fact alias to the .on() function. When you type in console: “jQuery.fn.bind.toString()” it will return: “function (a, b, c) { return this.on(a, null, b, c); }“.

Update 20/06/2012

$('selector').live(event, function(){ //do stuff here })

is now

$(document).on(event, selector, function(){ //do stuff here })

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.greglockwood.com/innerbattle Greg

    What about the pros and cons of using .on() versus .bind() or the shorthand methods like .click(), .focus(), .blur(), etc? Is there a benefit to one or the other in jQuery 1.7+?

    Or is .on() only best for scenarios where you would previously have used .live()?

    • jquery4u

      @Greg,

      As far as I’m aware, .on() has replaced .live() as of jQuery 1.7 but .bind() remains the same as it bind the event handler to the static element which exists at runtime and hence does not need to bubble up the DOM searching for more elements to attach event handlers to. As far as shorthand methods .click(), .focus() etc… they act the same as .bind().

      Correct me if I’m wrong.

      Cheers,
      Sam

      • Tomasz

        `bind` just maps to `on` – check line 3755 in jquery 1.7.1 dev file – so it’s there only for backward compatibility – it’s recommended to use on/off everywhere if you want to target only jquery 1.7+ as using bind will only add extra function call for every time you call a bind method

        • jquery4u

          @Tomasz,

          Great spot mate, I thought this was the case. I’ll update the post to include this now. Thanks again.

          Sam

  • Pingback: Meine Wochenlinks KW 49/2011 | Webocalypse

  • Pingback: Speed up your jQuery by Replacing Live with On | World Wide What?

  • http://www.maiconweb.com Maicon Sobczak

    Simple and effective explanation. I’ll migrate to .on()

    • jquery4u

      @ Maicon,

      Thanks mate, you’ll see an improvement!

  • http://zanematthew.com/ Zane Matthew

    What about content loaded via ajax that executes a script already loaded? I’ve always used .live for this, how would you achieve the same using .on?

    Demo here:
    http://demo.zanematthew.com/live-vs-on/

    • http://scurker.com Jason

      That’s kind of the point with live() vs on(). on() depends on the chained selector to actually exist, so $(‘selector’).live(‘event’, function) is nearly exactly the same as $(document).on(‘event’, ‘selector’, function);

      The added advantage of using .on() is you’re having to make a conscious decision about the original element(s) that you actually want to attach your delegated event to.

      • Radu

        Jason, I suggest adding a paragraph at the top of your post with this:

        $(‘selector’).live(event, function(){dostuffhere}) is now $(document).on(event, selector, function(){dostuffhere})

        This will make the bounce rate go through the roof :D

        Thank you for your useful article, new site bookmark in my browser.

        • http://jquery4u.com/ jQuery4u

          Thanks Jason, yes I’ll add it now although I think you might be right about the bounce rate! :)

    • paul

      serioius

  • Alon

    Great article !! now its all clear for me. Thanks !

  • Pingback: Pub Sub Pattern using jQuery .on() and .off() | jQuery4u

  • jquery4u

    Hi,
    I just read this article: http://www.jquery4u.com/jquery-functions/on-vs-live-review/ and does not agree that .on() method has completely replaced the .live() method.
    When I keep pressing on the min/plus button without hovering off the picture with the .live() method, the function works. In the case of .on() method the function does not work.
    How can I fix this issue for .on() method??
    Check out the demo so you can better understand what I’m referring too.
    http://jsdo.it/nouky/8UQ0
    Tnxx nouky

    • jquery4u

      Hi Nouky,

      I’m finding exactly the same thing as yourself.

      The on() function simply does not work 100% of the time with some code. So, I’m having to revert back to using .live() which obviously has it’s drawbacks.

      Do you mind me posting these emails into the comments for the post? In light of getting some feedback on the problem.

      Kind Regards,
      Sam

      • jquery4u

        Hi Sam,

        Ofcourse you can use these info to get feedback. I really would like to use the .on() method isntead of live because if you set an alert box in the function of .live(“click” function(){ etc etc }); you will see that the alert box keep reapearing. So if you hover 1 time u click on min button 1 alert box popup, when you keep doing this the amount will increase on the amount times that you hover on the text. With .on() method this is not the case.

        If we find a solution for the .on() method would be perfect!!

        ;-)

        • Mike

          Has the issue been resolved yet? Thx.

  • Pingback: .live() vs .on() method

  • Saeris

    The useful feature of .live() was that it allowed event binding on all future elements that meet the specified selector.

    How can you achieve the same delegation while using .on()?

    • http://scurker.com Jason

      I mentioned this above, but guess I should’ve read further. =)

      $(document).on(‘event’, ‘selector’, function) is nearly identical to $(‘selector’).live(‘event’, function);

      • Pedro Perez

        But, then the performance of .on over .live will not do any difference, right?

        • http://twitter.com/micahwedemeyer Micah Wedemeyer

          I think you’re right, but at least now you have the option of being more clever and trying to get a performance boost.

          If you’re just trying to get rid of deprecation warnings on legacy code, using $(document).on is probably the way to go.

  • chuwy

    So, if I’m understood it right, at now bind() is just a shortcut for the live()? Does it mean, that I can bind events on not-yey-appeared elements by bind()?

    • http://jquery4u.com/ jQuery4u

      Hi Chuwy, no you must use either on.() or .live() to capture events on new DOM elements, you use .bind() on elements which are loaded with the page. 

      Hope this is clear.
      Sam

  • http://jquery4u.com/ jQuery4u

    As of jQuery 1.7 the .bind() function is an alias to .on() function. When you type in console: “jQuery.fn.bind.toString()” it will return: “function (a, b, c) { return this.on(a, null, b, c); }“.

  • Jose3906

    Impresionante!, muy buena explicación al momento de querer programar en jQuery intentando ahorrar memoria para hacer un sitio WEB mas ágil :D, gracias!!

    • http://jquery4u.com/ jQuery4u

      Translated.

      Awesome!, Very good explanation when wanting to program in jQuery trying to save memory for a website more agile: D, thanks!

  • Pingback: Useful jQuery Function Demos For Your Projects | Layout to HTML

  • nigel

    I don’t like this. Instead of being able to do this
    $(‘.selector, .anotherselector, .somethingelse’).attr(something:’something’).live(‘click’,function(){something});
    i have to do this
    $(‘.selector, .anotherselector, .somethingelse’).attr(something:’something’);
    $(document).on(‘click’, ‘.selector, .anotherselector, .somethingelse’, function(){something});
    so should I need a list of selectors I have to maintain it twice.

  • Pablo

    Thanks a lot.

  • hg

    hghg

  • frontenddevfr

    Interesting post… I have read a lot of articles speaking about the “on” use and I think to use more… :-)

  • PM

    GREAT POST!, As an old school js programmer… I now feel the need for an update of my jquery libraries…. :D Thanks

    • http://jquery4u.com/ jQuery4u

      Thanks guys.

  • Elemental Web Development

    Thank you – great comment and also lovely visuals for the code depiction

  • Pingback: Useful jQuery Function Demos For Your Projects

  • http://twitter.com/platzh1rsch platzh1rsch

    Very well explained, thx!

  • Tácio

    parabens!! muito bom o post!

  • Pingback: события на узле DOM | e1r0nd

  • Pingback: 50 jQuery Function Demos for Aspiring Web Developers - Smashing Coding

  • Pingback: Cómo añadir eventos en jQuery de forma fácil y limpia | BorrowBITs

  • Pingback: Walidacja formularzy HTML5 za pomocą JS - doman.art.pl

  • Pingback: The tricky thing about replacing instances of jQuery’s live() with the on() method | Peter R Knight

  • Pingback: JQUERY 1.7+ .ON() VS .LIVE() REVIEW - LamaInteractives

  • Pingback: Useful jQuery Function Demos For Your Projects - Internet Business

  • Pingback: Deprecated Ajax Or JQuery Command Cause No Result Returned - PHP Solutions - Developers Q & A

  • Vivek Prakash Sharma

    Awesome!