Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

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

by

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!

Advertisement