2

I'm not sure why the interval isn't looping. I've followed tutorials exactly but not luck. Suggestions?

$(document).ready(function(){
  setInterval(function() {
    $('.current').removeClass('current').next().addClass('current');  
    }, 2000);
});

Updated: http://jsfiddle.net/pa7aU/3/

rbattle
  • 21
  • 2

5 Answers5

2

One possible ugly solution:

setInterval(function() {
    var $current = $(".current").removeClass("current"),
        $next = $current.next();

    if ($next.length)
        $next.addClass("current");
    else
        $current.siblings(":first").addClass("current");
}, 2000);

DEMO: http://jsfiddle.net/pa7aU/4/

VisioN
  • 143,310
  • 32
  • 282
  • 281
2
$(document).ready(function () {
    var $li = $('ul li'), i = 0, l = $li.length;
    setInterval(function() {
        $li.removeClass('current').eq(i % l).addClass('current');
        i++;
    }, 2000);
});

http://jsfiddle.net/chg4J/

Ram
  • 143,282
  • 16
  • 168
  • 197
0

When you reach the last element, you need to go back to the beginning, not use .next().

$(document).ready(function () {
    setInterval(function () {
        var next = $('.current').removeClass('current').next();
        if (next.length == 0) {
            next = $("li:first");
        }
        next.addClass('current');
    }, 2000);
});

FIDDLE

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

When you are at the last li, next() doesnt go to the first.

An easy fix is to add that after :

if($('.current').length <= 0) $('li:first').addClass('current');

Fiddle : http://jsfiddle.net/pa7aU/5/

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

Just to add something new to the mix:

$(document).ready(function () {
    setInterval(function () {
        $('li').eq(($('.current').removeClass('current').index() + 1) % $('li').size()).addClass('current');
    }, 200);
});
Blender
  • 289,723
  • 53
  • 439
  • 496