Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery fade to new image

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.

like image 537
user149109 Avatar asked Dec 29 '09 23:12

user149109


People also ask

What is fadeOut in jQuery?

jQuery Effect fadeOut() Method The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeIn() method.

What is the syntax of jQuery fadeIn () method?

The jQuery fadeIn() method is used to fade in a hidden element. Syntax: $(selector).fadeIn(speed,callback); The optional speed parameter specifies the duration of the effect.

How do you make a fade effect in Javascript?

onload=fadeIn, is used to call the fadeIn() function automatically. The fadeIn() function calls an in-built method setInterval(), which takes two parameters, one is function reference(show() in this case), and time interval(to take reference of function after selected interval).


2 Answers

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

like image 146
Ryan McGeary Avatar answered Oct 01 '22 18:10

Ryan McGeary


$("#main_image").fadeOut("slow",function(){
    $("#main_image").load(function () { //avoiding blinking, wait until loaded
        $("#main_image").fadeIn();
    });
    $("#main_image").attr("src","...");
});
like image 36
Yaakov Shoham Avatar answered Oct 01 '22 19:10

Yaakov Shoham