views:

1156

answers:

4

How can I fade one image into another with jquery? As far as I can tell you would use fadeOut, change the source with attr() and then fadeIn again. But this doesn't seem to work in order. I don't want to use a plugin because I expect to add quite a few alterations.

Thanks.

+1  A: 

Are you sure you're using the callback you pass into fadeOut to change the source attr and then calling fadeIn? You can't call fadeOut, attr() and fadeIn sequentially. You must wait for fadeOut to complete...

psychotik
+7  A: 

In the simplest case, you'll need to use a callback on the call to fadeOut().

Assuming an image tag already on the page:

<img id="image" src="http://sstatic.net/so/img/logo.png" />

You pass a function as the callback argument to fadeOut() that resets the src attribute and then fades back using fadeIn():

$("#image").fadeOut(function() { 
  $(this).load(function() { $(this).fadeIn(); }); 
  $(this).attr("src", "http://sstatic.net/su/img/logo.png"); 
}); 

For animations in jQuery, callbacks are executed after the animation completes. This gives you the ability to chain animations sequentially. Note the call to load(). This makes sure the image is loaded before fading back in (Thanks to Y. Shoham).

Here's a working example

Ryan McGeary
The problem is that the new image isn't loaded already hence there is a blink of the new image. (You can see it only if you have empty cache, of course)
Y. Shoham
I did say the "simplest case". Another way would be to preload the 2nd image either with javascript or with another hidden `img` tag. Fade out the original, then fade in the new.
Ryan McGeary
Or, you can use `load` event, to determine loading.
Y. Shoham
this will actually cause the image to fade into white then fade in again. The user probably want to fade directly from one image to another.
thephpdeveloper
Y. Shoham, Good call. Code updated.
Ryan McGeary
If the user want it without white-middle, so it's must to be done with background-loading, as Ryan said; although waiting for `load` is good practice anyway.
Y. Shoham
+1  A: 

Well, you can place the next image behind the current one, and fadeOut the current one so that it looks like as though it is fading into the next image.

When fading is done, you swap back the images. So roughly:

<style type="text/css"><!--
.swappers{position:absolute;width:500px;height:500px;}
#currentimg{z-index:999;}
--></style>
<div>
<img src="" alt="" id="currentimg" class="swappers" />
<img src="" alt="" id="nextimg" class="swappers" />
</div>

<script type="text/javascript">
function swap(newimg){
  $('#nextimg').attr('src',newimg);
  $('#currentimg').fadeOut('normal',function(){$(this).attr('src',$('#nextimg').attr('src')).fadeIn();});
}
</script>
thephpdeveloper
+2  A: 
$("#main_image").fadeOut("slow",function(){
    $("#main_image").load(function () { //avoiding blinking, wait until loaded
        $("#main_image").fadeIn();
    });
    $("#main_image").attr("src","...");
});
Y. Shoham