Search code examples
javascripthtmlcssbuttonshow-hide

Why my show hide button needs double-click on first time


I have this show/hide button on my website. It works, but on the first time the user needs to double-click it as if the switch is set to "hide" but the element is already hidden...

I'd like to edit my code so the button shows the element with a single click on the first time

I'm new to javascript, so I don't know how to change this.

Thank you

function showhidemenu() {
  var x = document.getElementById("menu");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>


Solution

  • To achieve expected result, use below option of checking display initially which will be empty if it is not inline

    x.style.display === "none" || x.style.display === ""
    

    Please refer this link for more details - Why element.style always return empty while providing styles in CSS?

    function showhidemenu() {
      var x = document.getElementById("menu");
      if (x.style.display === "none" || x.style.display === "") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
    #menu {
      background: rgba(0, 0, 0, 0);
      position: absolute;
      z-index: 1;
      top: 60px;
      right: 50px;
      width: 150px;
      font-family: 'Open Sans', sans-serif;
      display: none;
    }
    <div id="menu">This is a menu</div>
    <button onclick="showhidemenu()">Show/hide</button>