Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bubbling available for image load events?

Can I use:

window.addEventListner();

in some way.

All my images have a display = 'none'.

Once the image has loaded,

I want to set display = 'inline'

This way I can normalize what is displayed while the image is being downloaded.

In this case, I can not pre-load my images.


2 Answers

Use a capturing event listener on some parent DOM element like document, document.body or some other wrapper of images you need to observe. You can do this in the third argument of element's addEventListener method:

document.body.addEventListener(
    'load',
    function(event){
        var tgt = event.target;
        if( tgt.tagName == 'IMG'){
            tgt.style.display = 'inline';
        }
    },
    true // <-- useCapture (or options object)
);

The third argument can be either boolean (true) or newly added "options" object with a capture boolean property ({ capture: true }).

Using this approach, you don't have to (re-)attach event handlers while iterating through document.images live HTMLCollection or some (re-)queried static NodeList.

This is generally known as "event delegation pattern".

It will also work for dynamically inserted images.

And same applies to image's error loading events.

addEventListener at MDN

like image 118
myf Avatar answered Sep 09 '25 03:09

myf


The load/onload event does not bubble (reference, reference), so what you're asking for is not possible. You'll have to attach an event handler to each image node, or intercept the event during the capture phase, as suggested in other answers.

like image 27
bfavaretto Avatar answered Sep 09 '25 05:09

bfavaretto