chessweb
chessweb

Reputation: 4645

jQuery: simultaneously fadeIn and fadeOut

the following code which is called periodically by setInterval performs the following sequence:
1. fade in an image for 750 msec
2. diplay it for 6 secs
3. fade out the image for 750 msec
4. randomly select another image (function randomPic)
5. fade in for 750 msec and so on:

$("#_fadee_").fadeIn(750, function() {
    $("#_fadee_").delay(6000).fadeOut(750, randomPic);
});

You can see the effect here. How can I get the fadeOut of the old image and the fadeIn of the new one to run simultaneously?

Thanks, Ralf

Upvotes: 1

Views: 10749

Answers (2)

mVChr
mVChr

Reputation: 50185

Basically, you need to load the new image in another div that has a z-index beneath the image fading out. It's not that it's fading in simultaneously, it's just uncovered as the initial is fading out. Once the top div is faded out completely, you load the mew image into it and return its opacity to 1 so that it covers the div that you will load the next image into. In pseudocode it would look something like this:

var fadeO = function () {
    var $fo = $('#_fadeO_');
    var $fi = $('#_fadeI_');
    var newImg = // load image here;

    $fi.html(newImg);

    $fo.fadeOut(1500, function() {
        // put #_fadeO_ back on top with new image
        $fo.html(newImg);
        $fo.css({'display':'block', 'opacity':1});

        // call function again after 6 seconds
        setTimeout(fadeO, 6000);
    });
};

fadeO();

...but I made a fiddle of it so you could see it in action, switching background colors instead of image contents. You should be able to get the idea of how to do the same with loaded images based on the above pseudo-code and how the HTML, CSS, and JS is set up here:

http://jsfiddle.net/UbmS9/

Upvotes: 5

Robert
Robert

Reputation: 21388

If you aren't doing anything else you could do this:

$("#_fadee_").fadeIn(750, function() {
    setTimeout(function() {
        $("#_fadee_").fadeOut(750, randomPic);
        // Start fading in your other pic
    }, 6000);
});

Alternatively, if they're both being displayed in the same area, you could fade in, and once faded in set the background image to the next image. Then, once that's faded out, set the background to the next, and so on.

Upvotes: 1

Related Questions