Is there any way to bind to the load () event of an image after it changes src?

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

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

This second image (img2.png) is quite large, and I want to know when it is fully loaded (i.e...load () event). I tried using .live, .bind and .complete, but none of them work.

Any ideas?

Thanks! Amit

+4
source share
2 answers

I think the load event fires only once per img tag. But you can easily create a new image and load it using the new load handler.

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

After downloading, you can install src images on your page, and it will be pulled out of the browser cache instantly.

+4
source

You can do it:

 $('<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; }); 
+1
source

All Articles