1

I am trying to add and remove active class on multiple divs in a time interval using setTimeout(), addClass(), removeClass()...

function classAddRemove() {
  $("div").each(function(index) {
    setTimeout(function() {
      $("div").eq(index - 1).removeClass("active");
      $("div").eq(index).addClass("active");
    }, 500 * (index + 1));
  });
}

Code run once...and add remove active class in a 500ms interval...

Now I want that my function execute again and again...for that I tried to call my function inside itself.

function classAddRemove() {
  $("div").each(function(index) {
    setTimeout(function() {
      $("div").eq(index - 1).removeClass("active");
      $("div").eq(index).addClass("active");
    }, 500 * (index + 1));
  });
  classAddRemove();
}

But somehow the add and remove active class not executing again...I want to know where I am going wrong...I doubt is my code creating a infinite loop...?

Stack Snippet

$(document).ready(function() {
  function classAddRemove() {
    $("div").each(function(index) {
      setTimeout(function() {
        $("div").eq(index - 1).removeClass("active");
        $("div").eq(index).addClass("active");
      }, 500 * (index + 1));
    });
  }
  classAddRemove();
});
div {
  display: none;
}

div.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

1
  • Instead of setTimeout(), try using setInterval(), setInterval() will continue to fire off at the desired interval Commented Feb 5, 2018 at 17:17

1 Answer 1

1

If you want this to loop through the elements repeatedly it would make more sense to use setInterval(), then to go back to the first() element once the last one is reached. Something like this:

$(document).ready(function() {
  function classAddRemove() {
    var $divs = $('div');
    setInterval(function() {
      var $next = $divs.filter('.active').next();
      $divs.removeClass('active');
      
      if (!$next.length)
        $next = $divs.first();
        
      $next.addClass('active');
    }, 500);
  }

  classAddRemove();
});
div {
  display: none;
}

div.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

Sign up to request clarification or add additional context in comments.

1 Comment

how can i add class on button click ?

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.