0

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>
1
  • I think you'd want to use setInterval instead. Plus I think the logic is missing something. How do you know when it reaches the end? Why use each()? Commented Feb 17, 2012 at 23:47

3 Answers 3

1

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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.