-4

So as my title suggest. For a website I'm building, I need to add a class of 'active' to a list of <li> on the page.

Sometimes there will be six <li>, sometimes 17. It needs to be dynamic.

Then I need to add the class to each <li> in order, one at a time, every 5 seconds.


I was thinking, I could maybe have a counter to count all the <li>, and have a recurring function that adds the class to the first one and adds to another counter. When that counter hits the original counter for all the <li> it would stop. But then it would have to occur every 5 seconds.

Any help or advice would be appreciated

-JOPA

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
Jopa
  • 1

1 Answers1

0

Use .eq to select the element at index n within the matched set. Use setInterval to invoke the handler after specified-interval

var counter = 0;
setInterval(function() {
  var c = counter % $('li').length;
  $('li').removeClass('active');
  $('li').eq(c).addClass('active');
  ++counter
}, 5000);
.active {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Fiddle Demo

Rayon
  • 36,219
  • 4
  • 49
  • 76