We all use jQuery's AJAX helpers like $.get(), $.post() and $.load(). We also all use jQuery's event bindings. When you use them both, problems such as your event bindings like click() are not bided to your new AJAX loaded elements. To solve this problem you need to bind events to your newly loaded elements.
NOTE:
Make sure you don't bind the same event to the elements with this event already bound.
TIP:You should somehow separate newly created elements and then bind event in callback of an AJAX function.
Regarding the tip above. Here are two ways of separating AJAX loaded content:
- You can load into some specific container
<div id="ajax-loaded"></div>and then apply your events to the elements inside this container (Ex:$('#ajax-loaded .my-button').click(...)). - Add some class to your elements that are loaded on the server side.
Let's first bind click events to all our links.
// 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.
$.get('ajax-list.php', function(data){
$('#list').append(data);
});
Similarly, you could use .live() to add events to multiple div's in your ajax-loaded classed div
ex:
$("#ajax-loaded .my-button").live("click", function()
{
//do something
});
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-loadedclass to all your anchors that were loaded through AJAX and rebindclickevent to those links only ($('.ajax-loaded').click(...);). - The third way is to use event propogation. Search it on the jQuery blog.