1

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?

Tom
  • 75
  • 1
  • 8
  • [Load event's](https://developer.mozilla.org/en-US/docs/Web/Events/load) are not bubbled up so you cannot do event delegation with them – Patrick Evans Sep 09 '16 at 01:04
  • It might be worth having a look at the second answer using `complete` and `naturalHeight` to detect loaded images : http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript – kdvy Sep 09 '16 at 01:09

1 Answers1

0

You can simply add the event listener to the image after you have created it. Just note that you will need to create the image container separately. For example:

$('button').on('click',function(){
    var img = $('<img class="image" src="http://images.clipartpanda.com/ninja-clip-art-000056m.jpg" />');
    var imgContainer = $('<div></div>');
    imgContainer.append(img);
    $('#container').append(imgContainer);

    img.on('load', function(){
        $(this).after("This is a ninja");
    });
});

Updated fiddle here.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • Based on what I've read from the link above there may be issues with cached images in Chrome not triggering the load event - but then that answer was from 2013 everything could be different now! – kdvy Sep 09 '16 at 01:10
  • It looks like it is fixed. But regardless the question was about placing event listeners specifically, and not about image loading best practices. – Matt Way Sep 09 '16 at 01:13