I have the following code for going from div "mainFrameOne" to div "mainFrameTwo". However, it cannot go back to mainFrameOne after changing to mainFrameTwo. And I want it to be able to keep switching back and forth. How would I best acplish this?
HTML :
<div id="mainFrameOne">
<p>mainFrameOne</p>
</div>
<div id="mainFrameTwo" style="display:none;">
<p>mainFrameTwo</p>
</div>
<button onclick="myFunction()">Click me</button>
JS :
function myFunction() {
document.getElementById("mainFrameOne").style.display="none";
document.getElementById("mainFrameTwo").style.display="block";
}
I have the following code for going from div "mainFrameOne" to div "mainFrameTwo". However, it cannot go back to mainFrameOne after changing to mainFrameTwo. And I want it to be able to keep switching back and forth. How would I best acplish this?
HTML :
<div id="mainFrameOne">
<p>mainFrameOne</p>
</div>
<div id="mainFrameTwo" style="display:none;">
<p>mainFrameTwo</p>
</div>
<button onclick="myFunction()">Click me</button>
JS :
function myFunction() {
document.getElementById("mainFrameOne").style.display="none";
document.getElementById("mainFrameTwo").style.display="block";
}
Share
Improve this question
edited Feb 19, 2016 at 9:21
Zakaria Acharki
67.5k15 gold badges78 silver badges106 bronze badges
asked Feb 19, 2016 at 9:16
OneMoreQuestionOneMoreQuestion
1,7534 gold badges25 silver badges51 bronze badges
1
- 2 Possible duplicate of Toggle display:none style with JavaScript – Clemens Himmer Commented Feb 19, 2016 at 9:20
1 Answer
Reset to default 10Add condition to check if the div is visible then hide it and show the other one if else do the reverse :
function myFunction() {
var mainFrameOne = document.getElementById("mainFrameOne");
var mainFrameTwo = document.getElementById("mainFrameTwo");
mainFrameOne.style.display = (
mainFrameOne.style.display == "none" ? "block" : "none");
mainFrameTwo.style.display = (
mainFrameTwo.style.display == "none" ? "block" : "none");
}
Hope this helps.
function myFunction() {
var mainFrameOne = document.getElementById("mainFrameOne");
var mainFrameTwo = document.getElementById("mainFrameTwo");
mainFrameOne.style.display = (
mainFrameOne.style.display == "none" ? "block" : "none");
mainFrameTwo.style.display = (
mainFrameTwo.style.display == "none" ? "block" : "none");
}
<div id="mainFrameOne">
<p>mainFrameOne</p>
</div>
<div id="mainFrameTwo" style="display:none;">
<p>mainFrameTwo</p>
</div>
<button onclick="myFunction()">Click me</button>