Search code examples
javascriptonloadevent-bubbling

Listen for non-bubbling events on any element


Is there a way to listen for a non-bubbling event on any element in the DOM tree?

I want to listen for load events on any image that is created and loaded, without having to add events to every single image (this would also not work since new images can be created at any moment).

Is there any way of doing this?


Solution

    1. Add an event listener for the load event
    2. Check to see if the tagName is IMG
    3. You can use the capture phase of the event lifecycle by setting the second argument of .addEventListener() to true.
    document.querySelector('body')
      .addEventListener('load', el => {
          if (el.tagName === "IMG") { /* do something with the image load */ }
        }, true);