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
Share

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!

Jeffrey Way is JeffreyWay on Codecanyon

Related Posts

Add Comment

Discussion 32 Comments

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

  2. Elijah Manor says:

    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 ;)

  3. Paul Irish says:

    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.

  4. Kris says:

    Great tut! Please keep ‘em coming!

  5. web ders says:

    Great tut! Thanks

  6. Alexander says:

    Great Quick Tip. Hits the point perfectly.

  7. Fredrik says:

    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

  8. Aaron says:

    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”);
    });

    ?

    • Matt says:

      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.

  9. Max says:

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

  10. Aaron Godin says:

    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.

  11. flash says:

    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.

  12. Pavel Dominguez says:

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

  13. PablO says:

    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?

  14. David Runion says:

    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

  15. mike says:

    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.

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

  17. BlooApple says:

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

  18. Zy says:

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

  19. Martin says:

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

  20. Davidmoreen says:

    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.

  21. Thierry says:

    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.

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

  23. Ian Massey says:

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

  24. Oluwasogo says:

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

  25. Michiel says:

    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.

    • 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 says:

      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..

  26. bruce says:

    awesome. thanks for this simple explanation of delegate

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.