I've found plenty of examples to show/hide divs with a timeout in JavaScript, but I can't seem to solve my exact issue here.
I have six divs. I want to cycle through from 1 to 6 and then all over again, every 10 seconds. My current code is working as far as hiding the original div (always want div #one to show first on page load) after 10 seconds and showing the next one in sequence.
How can I cleanly cycle through these in order every 10 seconds?
$(document).ready( function () {
startCycle();
});
function startCycle(){
setTimeout(function(){
document.getElementById('one').style.display = 'none';
document.getElementById('two').style.display = 'block';
document.getElementById('three').style.display = 'none';
document.getElementById('four').style.display = 'none';
document.getElementById('five').style.display = 'none';
document.getElementById('six').style.display = 'none';
}, 10000); // 10000ms = 10s
}
#one{
display: block;
}
#two,
#three,
#four,
#five,
#six{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="one">Test One</div>
<div id="two">Test Two</div>
<div id="three">Test Three</div>
<div id="four">Test Four</div>
<div id="five">Test Five</div>
<div id="six">Test Six</div>
CodePudding user response:
I would suggest you put those div
elements in a container element, so you don't actually need the id
attributes anymore.
Then, as you use jQuery, use hide
and show
calls. You can use the remainder operator (%
) to "cycle" an index variable.
For the sake of quickly checking this solution, I reduced the delay to half a second:
$(document).ready( function () {
startCycle($("#container").children(), 0);
});
function startCycle($elems, i) {
$elems.hide().eq(i % $elems.length).show();
setTimeout(() => startCycle($elems, i 1), 500); // 500ms = 0.5s
}
#container > div { display: none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="container">
<div>Test One</div>
<div>Test Two</div>
<div>Test Three</div>
<div>Test Four</div>
<div>Test Five</div>
<div>Test Six</div>
</div>
CodePudding user response:
Maybe something like that ?
$(document).ready( function () {
const eList = document.getElementsByClassName('hideMe');
Object.keys(eList).forEach((elem, index) => {
setTimeout(function(){
toogle(eList[index])
}, 10000 * index);
});
});
function toogle(elem) {
if (elem) elem.classList.toggle('hide')
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="one" class='hideMe hide'>Test One</div>
<div id="two" class='hideMe hide'>Test Two</div>
<div id="three" class='hideMe hide'>Test Three</div>
<div id="four" class='hideMe hide'>Test Four</div>
<div id="five" class='hideMe hide'>Test Five</div>
<div id="six" class='hideMe hide'>Test Six</div>