Live vs Delegate: Fight!

Sorry for the week-plus break, but some good and hectic things have been going on. Back to writing…

Today, I talk about .live() and .delegate(), two jQuery functions that get lots of use. Both let you attach event handlers to elements. Although similar in application, I find .delegate() to be a much more precision instrument.

Let’s look at .live() first:

$(selector).live(event,data,function)

.live() is great. However, you can’t use live on child elements. Going deeper in the DOM isn’t just an option with .live().

However, as jQuery 1.4 rolled out, we were introduced to…

*drumroll*

.delegate()!!! (OK, the !!! aren’t part of the method, but I want some emphasis).

In addition to the event, the data passed and the function to be triggered, .delegate() adds the ability to select child elements.

$(selector).delegate(childSelector,event,data,function)

This way, you can select elements within other elements (such as <li> elements inside <ul>) and only affect the <li> element.

So Why Not Use .live() For Everything?

It would seem to save a lot of effort to use .live() for everything; just add a selector to narrow down .live() rather than use .delegate(). However, doing means that every time we click a link, .live() would have to check to see if it should trigger, moving upward from child elements all the way up to the top of the document. Every link, every time, even with a selector in place. However, .delegate() doesn’t have that issue. Rather than move all the way up to the document level, it will stop at the child selector indicated (for example, <ul>).

In a nutshell, .delegate() is less resource-intensive as it lets you narrow down the local section of the page, while .live() must process events in the entire page.

This entry was posted in jQuery and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s