I’m requesting data via AJAX and appending it to the page like so:
$('#post-images').append('<div class="image-holder"><img src="' + resp.images[i].imageUrl + '" /><br /><input type="checkbox" value="' + i + '" /></div>');
I’ve set up an event listener listening for the click event:
$('.image-holder').on('click', function() {
alert("testing");
});
However, the method never gets fired.
Using Chrome developer tools I can see that the correct HTML is being inserted onto the page, and the .image-holder div is getting clicked (it doesn’t have a 1×1 dimentions or something).
This code:
only binds event handlers to objects that exist at the time you run that code. If the objects are added to the page at some later time, they will not have event handlers on them.
Instead, you can use the delegated form of
.on()like this:This will bind a single event handler to
#post-imageswhich will catch the bubbling up clicks coming from any child objects that match the selector.image-holderso it will work with dynamically added objects.