Jesse Macleod
Jesse Macleod

Reputation: 285

Return to First Slide after reaching Last Slide - with jQuery Slider

I have a jQuery slider with an auto advance function. But I want to know how to return back to the first slide after the last slide is reached. The currentSlide variable (which holds the index of the current slide we are viewing) just keeps getting bigger and bigger, without returning to zero after the last slide is reached. I haven't included all of my jQuery script for the slider itself because that would be huge, and I think unnecessary. Here is the code:

<html>
<head>
</head>

<body>
<div class="slider" data-slide="0">
    <div class="slide"></div>
    <div class="slide"></div>
    <div class="slide"></div>
    <div class="slide"></div>
</div>

<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">

$(window).load(function(){
    var currentSlide = $(".slider").attr("data-slide"); /*Every time a slide is viewed, the index number of that slide is added to an html5 data- attribute. That way, we know what slide we are on. This var stores that information. */
    var timeOut = null;

    (function autoAdvance(){
        $('.sliderNav').find('.sliderTrigger' + (currentSlide)).trigger('click',[true]); /* Automatically click the trigger that will advance the slider to the next slide. */
        currentSlide++;
        timeOut = setTimeout(autoAdvance,5000);
    })();

});

</script>
</body>
</html>

Upvotes: 0

Views: 2094

Answers (1)

primetwig
primetwig

Reputation: 465

...
var currentSlide = $(".slider").attr("data-slide"); 
var timeOut = null;
count = $(".slider").children().length;

(function autoAdvance(){
    $('.sliderNav').find('.sliderTrigger' + (currentSlide)).trigger('click',[true]); 
    if (count == currentSlide){
        currentSlide = 1;
    } else {
        currentSlide++;
    }
    timeOut = setTimeout(autoAdvance,5000);
    })();
...

Upvotes: 1

Related Questions