When I first started using jQuery to make AJAX requests event delegation always caught me out as I never understood what it was or how to use it. If you’re manipulating the DOM you will surely come across the problem of when you dynamically add an element to a page you can’t just go and add an event handler to this new element and expect it to work. For instance say I have a list item which is clickable with the aid of a click event. If it’s setup so when I click the list item a completely new list item is automatically added to the page, without the use of event delegation or the function .live() the new list item won’t trigger the click function because the click function was initiated once our page was loaded, and since we added this item dynamically (meaning the page didn’t refresh) the event hasn’t been set to work with this new element.
Here’s an example of event delegation using the .live() function which is chained to our .click function.
The official jQuery documentation states: “The .live() method is able to affect html elements that have not yet been added to the DOM by using event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.”
$("document").ready(function() {
$("li").live("click", function(){
$(this).after("<li>Click here to add another list item</li>");
});
});
And the HTML:
<ul> <li>Click to add a list item</li> </ul>
You can find out more about the .live() method over at the official jQuery documentation.
Thumbnail picture credit ‘Bon Jovi Concert Stage 2007′: Anirudh Koul
This entry was posted in Javascript, Learn, Tutorials, headline, jQuery and tagged Javascript, jQuery, Tutorials. Bookmark the permalink.hehe i’ve seen and enjoyed the nettuts vid too…
Dont get me wrong, no offense (think i missed the tone)! I’ve just remarked that… i like your blog *flowers*
Subscribe to all the Papermashup Tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
Follow us on Twitter and get in-stream messages
4 discussions around jQuery Event Delegation