There’s no better way to express my problem than to show you an example. http://jsfiddle.net/CA6aQ/
$(document).ready(function() {
$('#foo').click(function(e) {
e.preventDefault();
$('#bar').addClass("herro");
});
$('.herro').click(function(e) {
alert("Hello World!");
});
});
Why doesn’t this work?
Thanks.
EDIT: To clarify, when I add a class to an element. The click event for that class trigger doesn’t fire.
Since the class is added dynamically, you have to use the
on()function (works with jQuery 1.7 and higher). For earlier versions uselive().Example.
Notice the difference in syntax. What we do is select the document, bind the click event to it, check if the click event was fired on the
.herroelement, and then fire the function. It works the same way as click except it will work with dynamic elements (in your case, the class you were selecting didn’t exist at the page load).