When adding dynamic content (using AJAX or DOM modification) using jQuery, events are not fired for the new objects, for example if you have the following html:
<button id="load" href="#">Test</button>
<div id="container"></div>
When I click the load button I want to add a link to another page inside the container DIV, so I use the following jQuery.
$(function() {
$("#load").click(function() {
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>")
});
$("#popup").click(function(){
alert("Clicked");
return false;
});
});
The click event for the dynamically created anchor tag (id="popup") will not fire using the above because this code is run once the document is ready, and at that time jQuery will look for an object with an Id of popup which doesn't exist yet.
I've found a few different ways to do this:
1. Add a generic click event for the body tag and check what was clicked, for example:
$("body").click(function(e){
var target = $(e.target);
if (target.is("#popup")) {
alert("Clicked");
return false;
}
});
Using this example you check what was clicked using target.is(), you can use any valid CSS selector statements to check the item clicked. This way is simple to implement but can quickly grow if you have a lot of dynamic content.
2. Use the
live command, which will tell jQuery to bind any current and future references of "#popup" to the click event.
$("#popup").live("click",function(){
alert("Clicked");
return false;
});
The following 3 ways are variations on the same theme in that the events are bound after content creation.
3. Use the jQuery
Bind command to bind the click event to a particular function on creation. e.g.:
$("#load").click(function(){
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>").bind('click', loadClick);
//can also use
//$("#container").html("<a id='popup' href='contactForm.html'>popup</a>").click(loadClick);
});
function loadClick(){
alert("Clicked");
return false;
}
4. Insert the function for handling the click event within the initial click event when you create the popup link. This runs the event binding as soon as the item is added.
$("#load").click(function(){
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>");
$("#popup").click(function(){
alert("Clicked");
return false;
});
});
5. Similar to the above method except this way you create a method which does all data binding (bindEvents()). This can be useful if you have a lot dynamic content that needs to be bound at the same time, it can be encapsulated into 1 event.
$("#load").click(function(){
$("#container").html("<a id='popup' href='contactForm.html'>popup</a>");
bindEvents();
});
function bindEvents(){
$("#popup").click(function(){
alert("Clicked");
return false;
});
};
There's also a plugin called
livequery that makes binding easier.