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>