Javascript toggle visibility: Requires me to click twice?

I want to add a simple toggle button to show/hide a popup.

I have the code below. It works, except for the fact that I have to click the button twice to show the hidden element.

<div id="toggle-wrap">
<p> I am the toggle stuff </p>
</div>


    <button onclick="adminToggle()">Edit</button>
    

<style> 
#toggle-wrap {display:none}
</style>

<script>function adminToggle() {
  var x = document.getElementById("toggle-wrap");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

</script>


It starts with no style display attribute, so it then sets it to block. The next time you click it sets it to none.

I would switch things around so that it checks for “block” instead.

  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }

Hang on, there are now three different states. When display is an empty string the stylesheet takes over, when it’s “block” it shows, and when it’s “none” it is hidden again.

Things get confusing there because there is both CSS and JS affecting the visibility of the element.

It would be better to remain consistent. Either use CSS to show and hide things, or use JS to show and hide things. But not a combination of both.

I would adjust your CSS so that you have a hide class, that JS can then toggle.

.hide {
  display: none;
}

You can then use that hide class to initially hide the element.

<div id="admin-content" class="hide">
<p> I am the toggle stuff </p>
</div>

And toggle that hide class from JS quite easily:

function adminToggle() {
  var x = document.getElementById("admin-content");
  x.classList.toggle("hide");
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.