1

Load event for images added dynamically to #div are not working, whereas other events like click/mouseover etc are working fine.

<div id="test">
  <img src="https://via.placeholder.com/50" />
</div>

js

$(document).ready(function() {
    // does not work
    $('#test').on('load', 'img', function() {
    alert('loaded');
  });

  // work fine
  $('#test').on('click', 'img', function() {
    alert('clicked');
  });
  setTimeout(() => {
    $('#test').append('<img src="https://via.placeholder.com/150" />');
  }, 1000);
  setTimeout(() => {
    $('#test').append('<img src="https://via.placeholder.com/250" />');
  }, 2000);
  setTimeout(() => {
    $('#test').append('<img src="https://via.placeholder.com/350" />');
  }, 3000);
});

check fiddle: https://jsfiddle.net/zkpt2crg/ any way to detect load event of dynamic elements?

coure2011
  • 40,286
  • 83
  • 216
  • 349
  • Unlike the most of jQuery events, `load` on images doesn't bubble, which is provided to delegate events. – Teemu Aug 28 '19 at 04:21
  • 1
    Implementation of the linked answer to your snippet: https://jsfiddle.net/x941gv3f/ – Kaiido Aug 28 '19 at 04:46

1 Answers1

0

You are simply not adding event to images, because your $('#test').on('load', 'img') doesn't see any images yet

Demo https://jsfiddle.net/710Ln2sa/

You should attach event to images explicitly

$(document).ready(function() {
  // extract to reusable function
  function onload () {
    alert('loaded');
  }
  setTimeout(() => {

    // create image
    const $img = $('<img src="https://via.placeholder.com/150" />')

    // attach load event
    $img.on('load', onload)

    $('#test').append($img);
  }, 1000);
});
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • That `on()` method attaches event behavior for elements that exist now and in the future - that's why the `click` event works. The question is, why does the same not apply to the `load` event? – Dacre Denny Aug 28 '19 at 04:10
  • are you sure about `attaches event to elements in the future`? Docs doesn't say anything like that – Medet Tleukabiluly Aug 28 '19 at 04:15
  • Have a look at this: https://jqueryhouse.com/jquery-on-method-the-issue-of-dynamically-added-elements/ – Dacre Denny Aug 28 '19 at 04:17
  • Also, see the way the click event is bound to images in the OP - try clicking all of the images – Dacre Denny Aug 28 '19 at 04:18