Skip to content Skip to sidebar Skip to footer

Jquery .attr() With Callback?

On my set I use jquery to fadeout an image, change its source to something else, then fade back in. However, sometimes on slow connections, the image will fade back in before the s

Solution 1:

Bind an event handler to the load event on the image, and fade it out in the handler.

Solution 2:

You need to preload the image, and handle the load event when your image is loaded.

var img = newImage();
$(img).load(function() {
  // Do fading and attr swapping stuff here// The new image is already loaded at this point
});

img.src = myImgUrl;

When the img is loaded your function will be called and your fade will happen. The image is now cached and ready to use and will show instantly.

Solution 3:

You are wanting to check when the image is loaded? .load() works.

Note: I've never seen it, but I've read that it can be triggered prematurely. So you may want to check the height of the image.

$(".img").fadeTo("fast",0,function(){
  $(this).attr({'src':url});
  $(this).load(function(){ 
    $(this).fadeTo("fast",1);
    $(this).unbind("load");
   });
});

Post a Comment for "Jquery .attr() With Callback?"