Eric Eric - 1 year ago 120
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)

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download