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

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>

Leave a Comment