I'm currently working on implementing a show and hide functionality for a div
. I followed a tutorial from a website called w3schools
, but the way they implemented it is different from what I'm looking to achieve. In their example, the div is initially shown and then you hide it, whereas in my case, I want it hidden by default and then shown when triggered. To do this, I simply added display: none;
to the #myDIV
element:
<!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;
display: none;
}
</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>
<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");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
However, when I first click the Try it
button, the div
doesn't show... Why is that happening? Subsequent clicks work as expected, showing and disappearing the div normally. How can I fix this issue? Thank you.