0

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);

1 Answer 1

2

A couple problems here:

  1. 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.

  2. When you hit your return statement - you never highlight anything.

  3. 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/

Sign up to request clarification or add additional context in comments.

3 Comments

Update implementation to remove all global variables.
thanks! What makes setTimeout the better option here?
@Marcatectura - you can make it work with either setInterval() or setTimeout(). I find it easier to use setTimeout() because you don't have to keep track of the timerID in order to stop the interval timer when you want to be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.