Looking to add an event listener to dynamically generated images. Here's a simplified example for ease of demonstration:
HTML
<div id="container">
<button>Click</button>
</div>
JS/jQuery
$('button').on('click',function(){
var $newImg = $('<div><img class="image" src="http://images.clipartpanda.com/ninja-clip-art-000056m.jpg" /></div>');
$('#container').append($newImg);
});
$('.image').on("load", function(){
$(this).after("This is a ninja");
});
See JSFiddle: https://jsfiddle.net/jd1pruvx/
I understand that the last bit of code which I want to work is run immediately, before the new images are loaded, so there are no images to place the event listener on.
My workaround was to use event delegation:
$(document).on('load', '.image', function(){
$(this).after("This is a ninja");
});
This doesn't work either. Any suggestions?