Search code examples
jqueryimagefadeoutrotator

jQuery rotator always snaps back to the first image


It's rather simple, after the last child img, the code snaps back to the first one, and for some reason fadeOut effect doesn't occur.

Here's HTML:

<div id="reel">
<img src="http://www.myweddingflowerideas.co.uk/wedding-flowers.jpg" />
<img src="http://www.aumflowersindiaflorists.com/images/flowers-chennai-1.jpg" />
<img src="http://img4.sunset.com/i/2008/12/image-adds-1217/alcatraz-flowers-galliardia-m.jpg?300:300" />
<img src="http://www.flowerslebanondelivery.com/catalog/images/Val101.jpg" />
<img src="http://www.weddingfloweridea.com/wp-content/uploads/2011/01/wedding-flowers-11.jpg" />
<img src="http://flowershopsflowers.com/wp-content/uploads/2011/04/Cardinal-Flowers.jpg" />
</div>

CSS:

#reel img{
position:absolute;
}

jQuery:

$(document).ready(function(){
$("#reel img:lt(5)").hide();
var counter = $("#reel img").length-1;

var i = setInterval(function() {

           $("#reel img").eq(counter).show();    
        $("#reel img").eq(counter - 1).show();
        $("#reel img").eq(counter).fadeOut(2000);
        counter--;

        if (counter === 0) {
            counter = 5;
        }
    }, 4000);

});

Check out this fiddle to see the problem in action: http://jsfiddle.net/FB9a9/

All that I want is the last image to fadeOut onto the first one, without snapping to it, so is there a way to do so?


Solution

  • The problem is that when you get to the end (0th image), the next image( 5th) comes after it in the markup, giving it a higher stacking order. Calling show() makes it visible on top and the other image fadeOut()s behind it. You may want to pull the img elements out of #reel and store them in an array, only adding them when they are being displayed.