Reputation: 1695
Background: I'm using jQuery to add a class to each <a>
element in a list one by one. I've got the addClass()
part working - the .highlighted
class is added to my first <a>
, then removed and added to the second, etc.
Problem: I haven't been able to get the addClass()
function to repeat once it reaches the last <a>
element. I understand from searching on SO that setInterval()
is a better way to approach this that setTimeout()
, which I was using initially, but I haven't figured out how to specify that the function needs to repeat. Any help appreciated!
HTML:
<a id="1">one</a>
<a id="2">two</a>
<a id="3">three</a>
<a id="4">four</a>
<a id="5">five</a>
JS:
var index = 0;
var $aArray = $('a');
function highlight(i){
if(i>0){
$aArray.eq(i-1).removeClass('highlight');
}
if(i == $aArray.length){
return;
}
$aArray.eq(i).addClass('highlight');
setInterval(function() { highlight(i+1) },2500);
}
highlight(0);
Upvotes: 0
Views: 1816
Reputation: 707308
A couple problems here:
You're starting a new setInterval()
on every call to highlight and never stopping the previous one so you get multiple timers running at once.
When you hit your return statement - you never highlight anything.
Your wrapping back to the beginning logic isn't implemented properly.
It is generally simplest to implement array wrapping using the %
operator. You can do something simpler like this:
function highlight(items, index) {
index = index % items.length;
items.removeClass("highlight");
items.eq(index).addClass('highlight');
setTimeout(function() {highlight(items, index + 1)}, 2500);
}
highlight($('a'), 0);
Working demo: http://jsfiddle.net/jfriend00/VLR4n/
Upvotes: 2