jQuery Event Delegation

2 February 2010| 4 Comments| Print

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.

How it works

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.

demo

Thumbnail picture credit ‘Bon Jovi Concert Stage 2007′: Anirudh Koul

4 Comments

  • RCKY

    hehe i’ve seen and enjoyed the nettuts vid too…

  • Ashley (author)

    @Rcky, ha ha I never even saw that post! for anyone else here’s a screencast over at nettuts.com which demonstrates a similar technique using regular javascript.

  • RCKY

    Dont get me wrong, no offense (think i missed the tone)! I’ve just remarked that… i like your blog *flowers* ;)

  • Ashley (author)

    @Rcky, Hey no worries none taken! Thanks for pointing it out its a great resource. This blog is all about helping other designers and developers and building a community so feel free to post useful tips and links anytime :) (thanks for the flowers) ;)

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.