Muhammad Abdullah Muhammad Abdullah - 7 months ago 23
HTML Question

How to change Visibility of Div

I want to change visibility of DIV on pressing of button . whats wrong with this code




<p id="myP">This is a p element.</p>

<button type="button" onclick="myFunction()">Hide content of p</button>

<script>
function myFunction() {
var which= document.getElementById("myP");

if (which.style.visibility=="visible")
which.style.visibility = "hidden"
else
which.style.visibility = "visible"
}

</script>

</body>



Answer

The original HTML doesn't have style="visibility: visible". So which.style.visibility returns null. Therefore, if(which.style.visibility) fails.

Add the explicit style and it should work.

function myFunction() {
  var which = document.getElementById("myP");

  if (which.style.visibility == "visible")
    which.style.visibility = "hidden"
  else
    which.style.visibility = "visible"
}
<p id="myP" style="visibility: visible;">This is a p element.</p>

<button type="button" onclick="myFunction()">Hide content of p</button>