Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a class name to the next sibling every N seconds

Tags:

jquery

I have a list as follows:

<ul>
  <li class="highlighted">Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

Every N seconds, I'd like to move the 'highlighted' class to the next element. When there's no more siblings, go back and start from the beginning.

Can someone help with the jQuery to accomplish this please?

Thank you!

like image 606
Mark Avatar asked Aug 21 '12 11:08

Mark


1 Answers

Something like this should do it:

HTML:

<ul id="myList">
  <li class="highlighted">Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

javascript:

$(function() {
    var lis = $("#myList > li"),
        currentHighlight = 0;
        N = 5;//interval in seconds
    setInterval(function() {
        currentHighlight = (currentHighlight + 1) % lis.length;
        lis.removeClass('highlighted').eq(currentHighlight).addClass('highlighted');
    }, N * 1000);
});

DEMO

like image 133
Beetroot-Beetroot Avatar answered Sep 30 '22 21:09

Beetroot-Beetroot