Jorge Gamito
Jorge Gamito

Reputation: 13

Jquery Infinite Loop not working

I've 3 divs that i want to highlight (with a css class) one after each other.After that the loop restarts and should do the same thing. But it isn't working.

Here's the fiddle http://jsfiddle.net/gamito/6M65S/

This must be something obvious ...

<script>
$('.ticker').each(function(i) {
var elem = $(this);
var prev = $(this).prev();
setTimeout(function() {
    elem.addClass("selected");
    prev.removeClass("selected");
}, i * 2000);
});​
</script>

Upvotes: 0

Views: 196

Answers (3)

jfriend00
jfriend00

Reputation: 707228

Based on the Ktash answer, here's a streamlined version:

// Setup an interval timer
setInterval(function () {
    var next = $('.ticker.selected').removeClass('selected').next('.ticker').addClass('selected');
    if(!next.length) {
        $('.ticker:first').addClass('selected');
    }
}, 2000);
// Initialize the selected class
$('.ticker:first').addClass('selected');

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

You an do something like, http://jsfiddle.net/6M65S/13/

var play = function(){
    var $ticker = $('.ticker'),
        $curTicker = $('.ticker').filter('.selected');
    $ticker.removeClass('selected');
    if(!$curTicker.is(':last')) {
        $curTicker.next().addClass('selected');
    } else {
        $ticker.first().addClass('selected');
    }   
};
setInterval(play, 1000);

Upvotes: 1

LoveAndCoding
LoveAndCoding

Reputation: 7947

Reworked your code. New fiddle here.

Basically, you want to switch around your thinking. Set up an interval, and change it on the interval, not on offsets on the setTimeout. Otherwise you would need to do setInterval in a setTimeout to make sure they were spaced evenly.

New Code:

// Setup an interval timer
setInterval(function () {
    // Get currently selected element
    var select = $('.ticker.selected');
    // Remove the class
    select.removeClass('selected');
    if(select.next('.ticker').length > 0) {
        // If we have more to go, select the next one
        select.next().addClass('selected');
    } else {
        // Otherwise restart
        $('.ticker').eq(0).addClass('selected');
    }
}, 2000);
// Initialize the selected class
$('.ticker').eq(0).addClass('selected');

Upvotes: 1

Related Questions