tags:

views:

37

answers:

2

Hi all, I have an image <img id='my_img' src='img1.png'> and a button. Clicking the button does the following:

$('#my_img').attr('src','img2.png')

This second image (img2.png) is fairly large, and I want to know when it is fully loaded (i.e. .load() event). I tried to use .live, .bind, and .complete but none seem to fire.

Any ideas?

Thanks! Amit

+2  A: 

I think the load event only fires once per img tag. But you can easily make a new image, and load that with a new load handler.

var img = new Image();
img.onload = function() {
  $('#my_img').attr('src', img.src);
};
img.src = 'img2.png';

Once it's loaded you can set the src of the image on your page and it will pull instantly from the browser cache.

Squeegy
Perfect, thanks! I guess there is no way to avoid creating a new image then.
AmitA
+1  A: 

You can do this:

$('<img id="myimg" src="1.png" /><a href="" id="clickme">click</a>').appendTo('body');

$('#clickme').click(function() {
    // replace the old img with a new one and define onLoad for the new img
    var newImg = $('<img />')
        .bind('load', function() {
            alert('2nd img loaded');
        })
        .attr('src', '2.png');
    $('#myimg').replaceWith(newImg);
    return false;
});
Biggie