0

I have a button that changes the visibility of a div. It turns it from being visible to hidden and then back every time it's pressed. How can I make the div stay hidden and make the button show it when it's pressed.

<script>
function Hide() {
    var x = document.getElementById("box");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
} 
</script>
<button id="Hidden" onclick="Hide()">Click me</button>
<div id="box"> 
 Sample text.
 </div>
Musty
  • 101
  • 1
  • 10
  • This is probably what you are looking for. [How can I change my button to instead of changing a div from visible to not visible, to do the opposite?](https://stackoverflow.com/questions/4528085/toggle-show-hide-div-with-button#4528100) – Roy Scheffers Jul 29 '18 at 13:47
  • Possible duplicate of [toggle show/hide div with button?](https://stackoverflow.com/questions/4528085/toggle-show-hide-div-with-button) – Roy Scheffers Jul 29 '18 at 13:49
  • As I checked the button is visible and div's CSS property is changing which is working fine.Then what do you want? – Prashant Pimpale Jul 29 '18 at 13:53

4 Answers4

2

Add style to the div - <div id="box" style ="display: none;">...</div>

Programmer
  • 1,973
  • 1
  • 12
  • 20
1
CSS - #box{display: none} //this will keep the element hidden on page load

function toggle() {
    var state = document.getElementById("box").style.display;
    if (state === "none") {
        state = "block";
    } else {
        state = "none";
    }
} 

<button id="Hidden" onclick="toggle()">Click me</button>
<div id="box"> 
 Sample text.
 </div>
ConsoleLog
  • 501
  • 3
  • 12
  • 1
    I'd also improve the code by removing the event handler from the button. var btn = document.getElementById("Hidden"); btn.addEventListener("click", toggle); // calling the toggle function written above – ConsoleLog Jul 29 '18 at 14:38
0

You can also add <script> tag at the end of the HTML code with calling the Hide() func Like this:

<script>
function Hide() {
    var x = document.getElementById("box");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
} 

</script>
<button id="Hidden" onclick="Hide()">Click me</button>
<div id="box"> 
 Sample text.
 </div>
<script>Hide();</script>
TalGabay
  • 238
  • 2
  • 9
0

you can also add the inline display none as below

<script>
function Hide() {
    var x = document.getElementById("box");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
} 
</script>
<button id="Hidden" onclick="Hide()">Click me</button>
<div id="box" style="display:none"> 
 Sample text.
 </div>
Hezbullah Shah
  • 888
  • 6
  • 16