Muhammad Arshad
Muhammad Arshad

Reputation: 11

Add class to list item alternately using JavaScript

I want to add an alternate class visible after 2 seconds to each element starting from 0 index. (like 0, 1, 2, 3, ... until the end).

When it comes to the last element, then add class to backwards like (10, 9, 8, ... until 0), so when on 0 again, forward and backward like an infinite loop. Thanks in advance for your help.

$(function() {
  iterate();

  function iterate() {
    var i = 0;
    var plus = setInterval(function() {
      i++;
      if (i == 10) {
        clearInterval(plus);
      }
    }, 1000);

    var minus = setInterval(function() {
      i--;
      if (i == 0) {
        clearInterval(minus); // again start plus interval
      }
    });

    $('li').removeClass('visible');
    $('li').eq(i).addClass('visible');
  }
});
.visible {
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ol>
  <li class="visible">One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li>Six</li>
  <li>Seven</li>
  <li>Eight</li>
  <li>Nine</li>
  <li>Ten</li>
</ol>

Upvotes: 0

Views: 651

Answers (1)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this: try below code where you can put logic to save current index and add / remove classes with setInterval function

$(function () {    
   var i = $("ol li").length;   
   var j =0;
   var down = true;
   setInterval(function(){
      if(i==j || j<0) {
        down = !down;
        if(j<0) {
           j=0;
        }
      }
      if(down) {
        $("ol li").eq(j).addClass("visible");
        j++;
      } else {
        $("ol li").eq(j).removeClass("visible");
        j--;
      }
   }, 2000);
});
 .visible {
        background: red
     }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol>
   <li>One</li>
   <li>Two</li>
   <li>Three</li>
   <li>Four</li>
   <li>Five</li>
</ol>

Upvotes: 2

Related Questions