jQuery infinite Carousel: Slide # 2 replaced by Slide # 3 on first iteration

718 Views Asked by At

I am building an infinite jQuery carousel. Infinite being that it shows the first slide right after the final slide is shown to the user. To achieve this, I make this little tweak in the post complete callback function

$('#slide li:last').after('#slide li:first').

This basically what makes the infinite slideshow happen. However, it messes up the second slide in particular. At the very first iteration of going from slide 1 to slide 2, slide 2 gets replaced by slide 3 (and it happens really quickly) . Every subsequent iteration works fine with slide 2 rendering itself as slide 2 and not slide 3.

To further understand this example, please take a look at the following js fiddle that captures all the necessary HTML, CSS, jQuery.

jsfiddle for jQuery infinite carousel/slideshow

Anybody know what's up :) ?

2

There are 2 best solutions below

0
Stepan Mazurov On BEST ANSWER

Its happening because upon the completion of the animation you're removing an li from the beginning of the ul and putting it at the end, thus reseting the left_indent by a multiple of 1 element.

A simple fix is to do $('#slides ul').css({'left': 0}); instead of $('#slides ul').css({'left': -item_width});

jsfiddle

1
Roko C. Buljan On

much simpler way:

jsBin demo

function slideshow(){

 var item_width = $('#slides li').outerWidth(true);

 $('#slides ul').stop().animate({left:-item_width},1200, function(){
     $('#slides li:last').after( $('#slides li:first') );
     $('#slides ul').css({left:0});
 });

}