Tuesday, December 14, 2010

Binding events to AJAX loaded content with jQuery

This is a demo for How to bind events to AJAX loaded elements blog post.

This is a static content

Let's first bind click events to all our links.
$(document).ready(function(){
    // Binding click events to all links
    $('#list a').click(function(){
        alert('I have a click event bind!');
    });
});


Now, let's try to AJAX load some additional list items to the above list. Please click here.
// AJAX load and append new list items to the list
$.get('ajax-list.php', function(data){
    $('#list').append(data);
});


Now, if you click on ajax loaded links in the list above they will not have click event binded to them.

There are 3 ways to overcome this issue:
  • Use .live() to automatically bind events to AJAX loaded elements (jQuery 1.3 and up).
  • Explicitly bind your event to the newly loaded AJAX elements. For example the list above add ajax-loaded class to all your anchors that were loaded through AJAX and rebind click event to those links only ($('.ajax-loaded').click(...);).
  • The third way is to use event propogation. Search it on the jQuery blog.

How to Debug Your jQuery Code

No comments: