Reputation: 67
I have been playing with setInterval and setTimeout to get one div to display before moving on to get the second div to display and then the third (final). After the final div displays I want to loop back to the first div to begin the process of toggling the divs again.
setInterval(function(){
$(".one").toggle();
$(".two").toggle();
}, 5000);
So I find that this loop works really well but when I introduce the ".third" div it skips the second and I am super confused!!
Upvotes: 0
Views: 83
Reputation: 2037
you need to iterate over your divs otherwise you are just toggling all of them every 5000ms, which might seem to work for only two divs, but not gonna work for more
pseudocode:
var divs = [$(".one"),$(".two"),$(".three")]
var index = 0
function focusNextDiv(){
//hide all divs
//select divs[index] and toggle it
//increment index by 1
//check if index is bigger than divs.length if so reset index to 0
}
setInterval(function(){
focusNextDiv()
}, 5000);
Upvotes: 0
Reputation: 781592
Give them all the same class, and use a counter variable that you increment each time to know which one to show. Use modulus to wrap around when you reach the last div.
var counter = 0;
setInterval(function() {
$(".class").hide();
$(".class").eq(counter).show();
counter = (counter + 1) % $(".class").length;
}, 2000);
.class {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class">
Div 1
</div>
<div class="class">
Div 2
</div>
<div class="class">
Div 3
</div>
<div class="class">
Div 4
</div>
Upvotes: 3