Quick Tip: The Difference Between Live() and Delegate()
videos

Quick Tip: The Difference Between Live() and Delegate()

Tutorial Details
  • Technology: jQuery
  • Difficulty: Intermediate
  • Completion Time: 5 Minutes

In jQuery 1.3, the team introduced the live() method, which allows us to bind event handlers to elements on the page, as well as any that might be created in the future dynamically. Though not perfect, it definitely proved to be helpful. Most notably, live() bubbles all the way up, and attaches the handler to the document. It also ceases to work well when chaining method calls, unfortunately. Delegate() was introduced in version 1.4, which almost does the same thing, but more efficiently.

We’ll examine the specific differences between the two methods in today’s video quick tip. Thanks to the FireQuery Firebug extension, we’ll have the tools to more easily understand how each method functions.

Alternate Viewing Options

<ul id="items">
	<li> Click Me </li>
</ul>
// Bind attaches an event handler only to the elements
// that match a particular selector. This, expectedly,
// excludes any dynamically generated elements.
$("#items li").click(function() {
	$(this).parent().append("<li>New Element</li>");
});
// Live(), introduced in 1.3, allows for the binding
// of event handlers to all elements that match a 
// selector, including those created in the future.
// It does this by attaching the handler to the document.
// Unfortunately, it does not work well with chaining.
// Don't expect to chain live() after calls like 
// children().next()...etc. 
$("li").live("click", function() {
	$(this).parent().append("<li>New Element</li>");
});
// Delegate, new to version 1.4, perhaps should have been a complete 
// replacement for Live(). However, that obviously
// would have broken a lot of code! Nonetheless, 
// delegate remedies many of the short-comings
// found in live(). It attaches the event handler
// directly to the context, rather than the document. 
// It also doesn't suffer from the chaining issues
// that live does. There are many performance benefits
// to using this method over live().
$('#items').delegate('li', 'click', function() {
	$(this).parent().append('<li>New Element</li>');
});
// By passing a DOM element as the context of our selector, we can make
// Live() behave (almost) the same way that delegate()
// does. It attaches the handler to the context, not
// the document - which is the default context.
// The code below is equivalent to the delegate() version
// shown above.
$("li", $("#items")[0]).live("click", function() {
	$(this).parent().append("<li>New Element</li>");
});	

Conclusion

This can definitely be a confusing topic. Please feel free to ask questions, or discuss within the comments. Thanks so much to Elijah Manor for clarifying a few things for me on this topic!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://blueprintds.com chicago web design

    Awesome, this CAN be a confusing issue for some. Great to see someone post it clearly and accurately. Thanks!

  • http://elijahmanor.com Elijah Manor

    I think you did a great job explaining a slightly confusing topic.

    It is good for developers to understand what is really going on.

    The FireQuery plugin definitely helps get the point across by showing any attached data() and event handlers to the HTML tab of Firebug.

    Thanks for mentioning my name too ;)

  • http://paulirish.com Paul Irish

    Good overview of the landscape, Jeffrey.

    Because live() is just so damn friendly a lot of people will likely continue to use it.
    But if they’re starting to look at performance, the gains that are available by using delegate() instead are enormous. So from a performance standpoint, it’s best to use delegate.

    For those that dig this stuff… if you read up on event delegation and learn how it works, this whole discussion becomes a lot more clear.

  • http://codemonkeys.biz Kris

    Great tut! Please keep ‘em coming!

  • http://www.webbu.org web ders

    Great tut! Thanks

  • http://edgespan.de Alexander

    Great Quick Tip. Hits the point perfectly.

  • http://oddtutorials.com Fredrik

    Really good explanation. The only thing you could’ve done better, would’ve been talking more slowly. I get really stressed listening to you. :p

  • Aaron

    So is:

    $(‘#items’).delegate(‘li’, ‘click’, function() {
    $(this).parent().append(‘New Element’);
    });

    really faster than:

    $(“li”, $(“#items”)[0]).live(“click”, function() {
    $(this).parent().append(“New Element”);
    });

    ?

    • http://twitter.com/matthew_maxwell Matt

      Yes.

      The reason is in the way that the jQuery object initializes.

      $(“li”, $(“#items”)[0]) queries for all li elements in #items.

      Since live doesn’t actually add the event handler to those li items, querying for them is inefficient and unnecessary.

      delegate attaches the event to #items, so querying for it makes sense.

      Also, you’re only querying for one element as opposed to many.

      If you had a very small amount of li elements initially, the performance wouldn’t be too big of a difference, but you’d still be making unnecessary queries to the DOM.

      • DN

        Ah! Great, that’s the explanation I was looking for. Thanks!

  • http://twitter.com/maxberndt Max

    thanks for the tip! haven’t used neither of them, but definitely will in the future!

  • http://www.aarongodin.com Aaron Godin

    Hey Jeffrey, thanks a ton. I know it only takes you a few minutes but it saves so much time for everyone, and I finally understand these events in relation to event delegation.

  • flash

    Very nice video and Im sure it will help others – certainly helped me.

    Plus I’m starting to really notice all the subtle changes to the site (unrelated I know) but think the design boys did a great job.

    cheers JW.

  • Pavel Dominguez

    Great tutorial. it was just what i needed for a current project.

    how would you go by using .live on events that have multiple handlers like say

    .hover( handlerIn(eventObject), handlerOut(eventObject) )

  • PablO

    So it’s like $( ‘#menu li’ ).live() is working while bubbling outside the #menu element, while $( ‘#menu’ ).delegate( ‘li’ ) stops working after it “bubbles” to #menu?

  • David Runion

    Another great jQuery article, thank you so much! I’ve been using .live() for awhile now and while I love the flexibility it gives me, I was unhappy to find that there are issues with using it in Firefox. I bound some tags’ click event, and it was triggering on right-click as well (!). Only in Firefox. Apparently it’s a long-standing Firefox issue.
    http://forum.jquery.com/topic/there-is-a-bug-for-btn-live-click-fn-on-firefox

  • http://tutorial-city.net Tutorial City
  • http://mikeosterhout@gmail.com mike

    Is it possible to use .delegate in the same fashion as the livequery plugin?

    For example if you do a partial load after an ajax call you need to make sure that your events will still fire on the loaded content.

    I have code like this

    $(‘#container’).livequery(function(){
    $(‘.something’).val(‘value’);

    $(‘a’).click(function() {
    //do something
    });

    // more things that need to be live
    });

    I like the above method because you only have to call the .livequery method once. Maybe this is unrecommended or maybe I should be doing this with .delegate.

    Anywho, keep up the javascript tutorials. You can never have too many of those.

  • http://www.315design.com Mikhail Kozlov

    Great one, Jeffrey. I wish every function in jQuery had that kind of inside information

  • BlooApple

    This is a great tut. Everytime i catch your new tut, i always get excited ! :D

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Thanks!

  • http://www.d3.lt Zy

    Hmm not bad really, I’ve learned something new today, thanks Jeff!

  • http://netnewmedia.com Martin

    Good stuff. These quick tips are very helpful for people who’ve got limited time.

  • http://thx2madre.tistory.com Irene

    Wow. Great!

  • http://spotdex.com Davidmoreen

    I just used the function live just the other day, man did it save me time. I had no clue how to get past the problem. One quick Google search turned up the jquery API, sure enough live was just what I was looking for.

  • http://www.ipadfactory.fr Thierry

    Very great quick tip, i didn’t even know the new live syntax with $(“li”,$(#items)[0])…. release on jquery 1.4 but thanks to you now i’m going to use delegate as often as i can.

  • http://ugur.ozyilmazel.com Uğur Özyılmazel

    nettuts+ rocks as usual! great effort! thanx a lot!

  • http://www.ianmassey.com Ian Massey

    This is as plain as I’ve seen it said. Very good explanation of a tricky subject. Thanks for sharing!

  • http://sogoojo.wordpress.com/ Oluwasogo

    Perfect way to end a Friday……nice one!!

  • Michiel

    Then why is live still there? You didn’t explain the advantages of live over delegate, if there are any. What I’m hearing is, “dump live and use delegate”. Now I do agree that currently, delegate is faster and is more precise, so less error prone. I am however still confused on what live is still doing there, because I don’t know why live should be used, now we have delegate.

    • http://www.mrnordstrom.com Daniel Nordstrom

      The comments of the code in the tutorial says:

      // Delegate, new to version 1.4, perhaps should have been a complete
      // replacement for Live(). However, that obviously
      // would have broken a lot of code!

      …which explains why live cannot be removed or replaced right away.

    • Bryan Kwon

      I think ‘live’ method shouldn’t be ditched soon even ‘delegate’ method covers all the benefits of ‘live’ method. I am pretty sure a lot of developers who are used to using ‘live’ method would confused more than anybody could imagine. Not really bad to have two options unless one of them is really worse than the other performance-wise..

  • http://incode.co.nz bruce

    awesome. thanks for this simple explanation of delegate

  • Virendra

    Awesome article. I found another article which defines the difference between all 3 methods bind, live and delegate.

    http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html

  • http://www.josegaldamez.com Jose Galdamez

    This tutorial just saved my hide. I was using .live() in an Ajax app and all was working fine until I tested in IE7. No matter what my click handlers would not stick on my dynamic checkboxes. I switched to .delegate() and it instantly started working. Thank you for the great explanation!

  • rajilesh

    hi nettuts guru, I’ve an issue with click funtion. ie, click works only onetime. what is the reason behind it?

    NB: there is no relation with this topic.

  • http://www.timacheson.com/ Tim

    I took the liberty of summarising this excellent post and other useful comments in one place, for my own record and in case this anyone else finds it useful. I link to this page in my summary.

    JQuery live vs delegate vs bind: http://www.timacheson.com/Blog/2011/oct/jquery_live_vs_delegate