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.
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/
//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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With