I have the following code. By default it shows, but I want to hide it by default.
Also, I'm unable to control both of the divs, only 1 of the show/hide toggles work, I want for them (but have been unsuccessful) both to work.
How can I hide by default and expand on click?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction()">Try it 2</button>
<div id="myDIV2">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
You are overwriting your x
variable. Assign myDIV2
to another variable like y
and repeat the process.
Better would be to just assign the same class
instead of id
to the elements you want to hide and just toggle the class instead of trying to get each element by id.
https://ultimatecourses.com/blog/javascript-hasclass-addclass-removeclass-toggleclass
Just separate the function on the first and scond button
function myFunction_1() { var x = document.getElementById("myDIV"); var y = document.getElementById("myDIV2"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } function myFunction_2() { var y = document.getElementById("myDIV2"); if (y.style.display === "none") { y.style.display = "block"; } else { y.style.display = "none"; } }
#myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; }
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction_1()">Try it</button> <div id="myDIV"> This is my DIV element. </div> <br><br> <button onclick="myFunction_2()">Try it 2</button> <div id="myDIV2"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.