Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add and remove a class in a loop with jquery

Tags:

jquery

loops

A simple loop is what I am looking for, I have a button and all that's needed is a simple loop to add and remove a class to an element.

    <div id="button" class="animate">

    </div>

What I want to do is loop over 3 times and add and remove a class to the #button.

So initially when the screen loads it will render as above, after 2 seconds the animate class will be removed then after 2 more seconds the 'animate' class is added, then removed and this loops for x amount of times.

like image 844
user2430293 Avatar asked Jan 25 '26 06:01

user2430293


2 Answers

Something like this:

$(document).ready(function() {
    var loops = 3 * 2;
    function removeAddClass() {
        $("#button").toggleClass("animate");
        if (--loops > 0)
             setTimeout(removeAddClass, 2000);
    }
    removeAddClass();
});

Demo: http://jsfiddle.net/26GUe/

like image 162
nnnnnn Avatar answered Jan 27 '26 23:01

nnnnnn


//Create a var to store the index of red element
var count = -1;
function AddRedClass() {
  var boxes = $('.box');
  var boxLength = boxes.length - 1;
  //Check if the actual item isn't more than the length then add 1 otherway restart to 0
  count < boxLength ? count++ : count=0;
  //Remove the class and add it to the new target
  boxes.removeClass('red').eq(count).addClass('red');
}
setInterval(AddRedClass, 1000);
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 250px;
}
.box {
  width: 30%;
  border: 1px solid green;
  transition: background .3s linear;
}
.red {
  background: red!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box">
    c-1
  </div>
  <div class="box">
    c-2
  </div>
  <div class="box">
    c-3
  </div>
  <div class="box">
    c-4
  </div>
  <div class="box">
    c-5
  </div>
  <div class="box">
    c-6
  </div>
  <div class="box">
    c-7
  </div>
  <div class="box">
    c-8
  </div>
  <div class="box">
    c-9
  </div>
</div>
like image 39
Bhargav Patel Avatar answered Jan 27 '26 23:01

Bhargav Patel