user2381114
user2381114

Reputation: 471

Infinite each() loop in jQuery?

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.

Upvotes: 1

Views: 182

Answers (2)

Itay
Itay

Reputation: 16777

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

Upvotes: 5

techfoobar
techfoobar

Reputation: 66663

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/

Upvotes: 4

Related Questions