Eric Eric - 6 months ago 43
Javascript Question

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(){


$('.tile img').on('load', function(event){

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)


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.

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

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

    $(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() {

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