Rivsen
Rivsen

Reputation: 431

why jquery on() not work on image load event

$('body').on('click', 'img', function () {
    $('<img class="halfsize" src="imgs/logo.png?' + Math.random() + '" alt="" />').appendTo('header');
});
$('img').on('load', function (evt) {
    console.log(this, evt);
});

This code work fine when page first load. But, when click img, new append to header's img not trigger the load event, why? Click event is work well.

Upvotes: 0

Views: 1966

Answers (2)

jfriend00
jfriend00

Reputation: 708056

For some browsers (IE in particular), you MUST attach the onload handler BEFORE you assign the .src attribute. That's because some browsers will load an image immediately when you assign the .src attribute if the image is in the image cache. Thus, if you attach the load handler afterwards, the event will already have occurred and you may miss the event entirely.

The load event does not propagate so you cannot use delegated event handling for it.

In your case, I would suggest this code for safe, proper behavior in all browsers that attaches the load handler first:

$('body').on('click', 'img', function () {
    $('<img class="halfsize" alt="" />')
        .on('load', function (evt) {
            console.log(this, evt);
         })
        .attr("src", "imgs/logo.png?" + Math.random())
        .appendTo('header');
});

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196256

The click works because you use the delegated form of .on().

You should do the same with the image..

$('header').on('load','img', function( evt ){
    console.log(this, evt);
} );

Update Seems that image load events do not bubble up the DOM (so you cannot handle them through delegated event handlers)..

So you will have to manually add your handler to the dynamically added images..

function loadHandler(evt){
    console.log(this, evt);
}
$('body').on('click', 'img',function(){ 
    $('<img/>', {
        'class':'halfsize',
        load: loadHandler,
        alt:'',
        src: 'imgs/logo.png?'+ Math.random()
    }).appendTo('header'); 
});

$('img').on('load', loadHandler);

Upvotes: 3

Related Questions