Razor Storm
Razor Storm

Reputation: 12326

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 source completely changes, so the old image will still appear for a brief second before the new one comes in.

Is there a way to have a callback on attr so fading back in is only called when the attr change is reflected?

$(".img").fadeTo("fast",0,function(){
    $(".img").attr({
        //some other stuff
        'src':url
    });
    $(".img").fadeTo("fast",1);
    //other stuff
});

I use fadeTo not fadeIn() so the image size is retained.

Upvotes: 0

Views: 5418

Answers (3)

Neon Physics
Neon Physics

Reputation: 3477

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");
   });
});

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187014

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

var img = new Image();
$(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.

Upvotes: 0

Jimmy
Jimmy

Reputation: 37081

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

Upvotes: 2

Related Questions