Dan7
Dan7

Reputation: 1727

jQuery: fadeIn/fadeOut doesn't work on images the first time

I have a simple slideshow of images and use jQuery to fade out one and fade in another, and change z-index accordingly. But the effects only work after the first time. As shown here: http://jsfiddle.net/AXMX8/1/ (same behaviour in my test file)

I thought it might have to do with image not being loaded yet, so I tried wrapping the code with $(window).load() in my test file, but it was still the same.

function fadeSlide($out, $in) {
    $out.fadeOut("slow", function(){
        $(this).removeClass("slide-active");
    });

    $in.fadeIn("slow", function(){
        $(this).addClass("slide-active");
    });
}

function switchSlide() {
    var imgs = $('#slides img');
    var current = $('.slide-active');
    var next = current.next();
    if (next.length == 0) {
        next = imgs.eq(0);
    }
    fadeSlide(current, next);
}

setInterval(switchSlide, 2000);

Thanks for any help.

Upvotes: 1

Views: 1901

Answers (1)

Hubert OG
Hubert OG

Reputation: 19544

When the function runs for the first time, the image it takes as the $in variable is visible. Therefore, the fade-in does not appear, as it requires the desired image to be invisible. The image just flips to the front.

Here's a simple solution. Last line was replaced with:

$(function(){
    $('#slides img').hide();
    $('#slides img').first().show();
    setInterval(switchSlide, 2000);
});

Upvotes: 1

Related Questions