javascriptjqueryhtmlimage-galleryjquery-slider

Why is my jquery div slider skipping some of the divs?


http://jsfiddle.net/czt0mycw/

<body>
<div id="hold_divs">hold divs
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
</div>
</body>

This is my first time building a jquery slider and it is exhibiting the strangest behavior. When the page first loads, it slides(automatically) the contents(my 4 divs stacked on top of one another) to the right successfully. But after a full slide show is completed, the slider no longer displays div1(the div with the red background). Instead, it skips(I believe that's whats happening) and shows the parent div("hold_divs").

When I was debugging, I altered the code to slide in only 2 divs, and a similar error occurred. This time, the two divs slid correctly only once (when the page is first loaded). After the first slide show completed successfully, it displayed the first of the 2 divs, but the 2nd div in the was not displayed; the 3rd div in the array was. O.o http://jsfiddle.net/czt0mycw/1/


Solution

  • You need to reset the divs on the next iteration of the interval. Change:

    setInterval(function()
        {
    
        var divs=[$("#div4"),$("#div3"),$("#div2"),$("#div1")];
        var width=divs[x].width();
        divs[x].stop().animate({right:"100%"},"slow");
        x+=1;
        if(x==4)
        {
         $("#div4,#div3,#div2,#div1").css("right",0);
            x=0;    
        } 
    },3000);
    

    to

    setInterval(function()
    {
        if(x==4)
        {
            $("#div4,#div3,#div2,#div1").css("right",0);
            x=0;
            return;
        } 
        var divs=[$("#div4"),$("#div3"),$("#div2"),$("#div1")];
        var width=divs[x].width();
        divs[x].stop().animate({right:"100%"},"slow");
        x+=1;
    
    },3000);
    

    What's happening is that you're resetting the divs immediately after you start the animation for the 4th div. Instead, you want to reset the divs immediately before you start the animation again for the 1st div.