Eric
Eric

Reputation: 10658

dynamic image onload after append?

I'm facing the problem that, after i append a bunch of images in a div (one per div) to a container (div), i don't get the onload function..

this is in a loop including a bunch of variables

$('#container').append('<div class="tile" style="position:absolute; top:'+(i*size)+'px; left:'+(j*size)+'px; width:'+size+'px; height:'+size+'px; overflow:hidden;" ><img src="'+map[i][j]+'"/></div>');

All variables are fine and all images are loaded correctly but this never works

$('.tile img').live('load', function(){
console.log("loaded");
});

or

$('.tile img').on('load', function(event){
console.log("loaded");
});

I've tried with the newer .on jQuery function, and no go..

Edit : [+]added .on code (both functions are placed on top right after document ready)

Upvotes: 3

Views: 9084

Answers (2)

Erick Maynard
Erick Maynard

Reputation: 801

I know this is an old post, but I recently had to deal with this exact issue, and found a slightly simpler solution:

$(".container").append(yourImageOrImages);
setImages();

function setImages() {
    $(".container img").each(function() {
        $(this).on('load', function(){
            // Your code to run when done loading
        });
    });
}

Upvotes: 3

lucuma
lucuma

Reputation: 18339

Update: I played around with it a bit and the following strategy also works for the load event on a newly created image. First I'm creating the image then appending it into the div before appending that to the document.

http://jsfiddle.net/lucuma/sHGm9/1/

$('.slideshow').each(function(i) {

    var $img = $('<img src="..." />').on('load', function(){
        alert('loaded');
    });

    $(this).append( $('<div class="tile" style="" ></div>').append($img) );               
    // you'd need to just use your div example here

});

Original Answer:

I can think of two things.. Add the on/live before you append or change it to something like this:

var $img = $('<img src="..." />');

$img.on('load', function() {
    alert('loaded');
});

$('#slideshow').append($img);  // adapted for my example

http://jsfiddle.net/lucuma/sHGm9/

Upvotes: 10

Related Questions