Sorry for the week-plus break, but some good and hectic things have been going on. Back to writing…
Today, I talk about
.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() is great. However, you can’t use live on child elements. Going deeper in the DOM isn’t just an option with
However, as jQuery 1.4 rolled out, we were introduced to…
.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.
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.