MailCarrier
MailCarrier

Reputation: 101

How to crossfade an image with jQuery

I'm trying to crossfade an array of images, that transfer smoothly between each one, for a slideshow. I've tried fadeIn and fadeOut, and fadeTo but none seem to create the crossfade effect. None of the other articles on here could answer my question exactly.

The function isn't entirely finished, so I know the images won't reset, I'm just trying to get the crossfade to work.

$(function() {

    var slides = ["images/slideshow1.jpg", "images/slideshow2.jpg", "images/slideshow3.jpg", "images/slideshow4.jpg", "images/slideshow5.jpg"];        
    var slidePos = 0;

    setInterval(function() {    
        slidePos++;

        $("#slideshow-image").fadeOut(500).fadeIn(1000).attr("src", slides[slidePos]);
    }, 3000);
});

Actual: Image switches to next then fades out, then fades in Expected: Cross-Fade

Upvotes: 0

Views: 232

Answers (1)

John
John

Reputation: 6278

You must make a second image element with the opacity of zero and have it overlap by having its position set to absolute.

Then animate its opacity to 1.0 and remove the old image element which is now hidden underneath the new one.

Then repeat this process.

You don't have to create new elements if you just have two and cycle between them.

Upvotes: 1

Related Questions