Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

css and js show-hide function works on 2nd click only

I have this code:

function UnhideFunction() {
  var x = document.getElementById("MyShow");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
.myhide {
  display: none;
}
<button onclick="UnhideFunction()">SHOW ME</button>
<div id="MyShow" class="myhide">
  SOME TEXT

The problem is SOME TEXT shows only when I click SHOW ME twice.

How do I fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

The issue you’re encountering is likely due to how the display property is being set and checked. When you initially hide the element by setting display: none;, the x.style.display property will be an empty string, not "none".

This will fix the problem

<script>
function UnhideFunction() {
  var x = document.getElementById("MyShow");
  if (getComputedStyle(x).display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading