i want to replace divs using onclick() in a way that they seem to rotate from the default div1 to div2 to div3 and back to div1 and over and over again.
i have with me something i have made that is working just fine but i am stuck trying to make it return to the default condition (conditions) and rotate the function show() from start to end and end to start.
this is the code i have that is working just fine but not executing the function show() from start to end and end to start
<!DOCTYPE html>
<html>
<body>
<div style="margin-left:30%;margin-bottom:20%;">
<div id="div1" style="display:block">
<h2>one</h2>
</div>
<div id="div2" style="display:none">
<h2>two</h2>
</div>
<div id="div3" style="display:none">
<h2>three</h2>
</div>
<div id="div4" style="display:block">
<h2>one under</h2>
</div>
<div id="div5" style="display:none">
<h2>two under</h2>
</div>
<div id="div6" style="display:none">
<h2>three under</h2>
</div>
<button onclick=show()>click here</button>
</div>
</body>
<script>
function show() {
let div1 = document.querySelector('#div1');
let div2 = document.querySelector('#div2');
let div3 = document.querySelector('#div3');
let div4 = document.querySelector('#div4');
let div5 = document.querySelector('#div5');
let div6 = document.querySelector('#div6');
if (div1.style.display == "block" && div4.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
div4.style.display = "none";
div5.style.display = "block";
} else {
div1.style.display = "block";
div2.style.display = "none";
div4.style.display = "block";
div5.style.display = "none";
}
if (div2.style.display == "block" && div5.style.display == "block") {
div2.style.display = "block";
div3.style.display = "none";
div5.style.display = "block";
div6.style.display = "none";
} else {
div2.style.display = "none";
div3.style.display = "block";
div5.style.display = "none";
div6.style.display = "block";
}
if (div3.style.display == "block" && div6.style.display == "block") {
div2.style.display = "none";
div1.style.display = "none";
div3.style.display = "block";
div5.style.display = "none";
div4.style.display = "none";
div6.style.display = "block";
}
}
</script>
</html>
2
Answers
This is very old school code using pure JS and document.querySelector.
My recommendation for this code is to use JQuery.
See the toggle method https://www.w3schools.com/jquery/eff_toggle.asp
One simpler way is as follows
Another way: