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.
3 Answers 3
Bind an event handler to the load event on the image, and fade it out in the handler.
Comments
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.
2 Comments
.load() on the same element get re-triggered if it has already been triggered once?load event exactly once to that object. And even if the image is already loaded, the load is event is still triggered and handled. So there is no "same element" here at all since its a new object each time.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");
});
});
5 Comments
.load() would re trigger if it has already been re-triggered. @Squeegy has a solution below if it does, this one is a solution if it doesn't. I remember something fishy happening when I used to use .load().$() four times, you should only be calling it once