user2797454
user2797454

Reputation: 77

JS .fadeOut not fading correctly

Trying to get the image to fade out slower but it appears to just fade instantly, I'm then left with white space while the new image loads.

HTML

<div class="fadein">
   <!--<img src="images/me.jpg" alt="" /> -->
   <img src="images/boatResized.jpg" alt="" />
   <img src="images/carResized.jpg" alt="" />
   <img src="images/dennis_stockRezied1.jpg" alt="" />
</div>

JS

$('.fadein img:gt(0)').hide();

setInterval(function () {
    $('.fadein :first-child').fadeOut(4500)
        .next('img')
        .fadeIn(5500)
        .end()
        .appendTo('.fadein');
}, 8000); // 8 seconds

Im fairly new to JS and having trouble getting this to function correctly.

Upvotes: 0

Views: 54

Answers (1)

nnnnnn
nnnnnn

Reputation: 150020

The main problem is that your call to .fadeIn() does not wait for the .fadeOut() to complete because they are called on different elements (and so belong to different animation queues). You could add a completion callback function as a second argument to .fadeOut() and then do the .fadeIn() within that function.

Note also that you are using an 8 second interval, but your fades are 4.5 and 5.5 seconds, which adds up to a 10 second turnaround. So in the following code I've increased the interval to 11. I tried to do this with as few changes to your code as possible:

setInterval(function () {
    $('.fadein :first-child').fadeOut(4500, function() {
        $(this).next('img')
               .fadeIn(5500)
               .end()
               .appendTo('.fadein');
    });
}, 11000);

Demo: http://jsfiddle.net/qh03e16s/

You could also get rid of the setInterval(), and instead trigger each fade sequence from the completion callback of the .fadeIn(). Then you don't have to worry about timing the interval to add up to the fade out and in, although it means the first fade begins immediately:

(function doFade() {
    $('.fadein :first-child').fadeOut(4500, function() {
        $(this).next('img')
               .fadeIn(5500, doFade)  // note the doFade reference
               .end()
               .appendTo('.fadein');
    });
})();

Demo: http://jsfiddle.net/qh03e16s/1/

Upvotes: 1

Related Questions