Reputation: 21
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/
Upvotes: 2
Views: 326
Reputation: 298532
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);
});
Upvotes: 0
Reputation: 33880
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/
Upvotes: 0
Reputation: 144729
$(document).ready(function () {
var $li = $('ul li'), i = 0, l = $li.length;
setInterval(function() {
$li.removeClass('current').eq(i % l).addClass('current');
i++;
}, 2000);
});
Upvotes: 2
Reputation: 782498
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);
});
Upvotes: 0
Reputation: 145458
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/
Upvotes: 2