1

I have a few separate headings:

<h3 class="ads">First</h3>

<h3 class="ads">Second</h3>

<h3 class="ads">Third</h3> 

And I'd like to be able to continuously loop over them, changing the text from black to red, and then back to black once the next heading has changed to red.

Here's what I have so far: it works once, however I cannot get it to re-loop succesfully:

$('.ads').each(function(i) { 
    var el=$(this);
    setTimeout(function() {
        el.prevAll('.ads').css('color','black');
        el.css('color', 'red');
    }, i * 3000); 
});

I'd like to be able to manually set how long I wait in between each change, so an explanation would help a lot too!

Here's the jsFiddle.

3
  • 1
    use setInterval rather than setTimeout for starters maybe. Commented Sep 22, 2013 at 15:19
  • 2
    @d'alar'cop: Er, why? Commented Sep 22, 2013 at 15:19
  • Sorry, don't you want it to keep going? Maybe I misunderstood. Never mind. Commented Sep 22, 2013 at 15:20

2 Answers 2

5

Here's a slightly different approach.

jsFiddle Demo

var $headings = $('.ads'),
    $length = $headings.length,
    i = 0;

setInterval(function() {
    $headings.css('color','black');
    $headings.eq(i).css('color', 'red');
    i = (i + 1) % $length;
}, 3000); 
Sign up to request clarification or add additional context in comments.

3 Comments

$($headings.get(i)) mein got... Use $headings.eq(i) instead.
Sorry but what language is this?
It is and I've updated it because it is a good suggestion. But "mein got" doesn't look like English.
4

You can use recursion to do this elegantly.

// configure the delay
var delay = 1000;

// save a pointer to the first element
var first = $('.ads').first();

// this function does the following
// a. color the current element red
// b. make all siblings black
// c. call itself with the next applicable element
function change(_elem) {
    _elem.css('color','red').siblings().css('color', 'black');
    setTimeout(function() {
        change((_elem.next().length > 0) ? _elem.next() : first);
    }, delay);
}

// start if off
change(first);

Demo: http://jsfiddle.net/gNrMJ/16/

Comments

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.