Search code examples
javascripthtmlcss

How can I show a hidden text by clicking on a button?


function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display = "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<ul>
  <li><button onclick="myFunction()">Try it</button>
    <div id="myDIV"><p>This is my DIV element.</p></div 
  </li>
</ul>

In the css file I included the command: #myDIV{ display: none; } because otherwise the text would not be hidden at first. With this code the text is hidden at first and if I click on the button it shows the text. But then if I click on the button again it should be closing the text which it does not. Can someone help me out here? Thanks!


Solution

  • Set this to HTML

    <div id="myDIV" style="display: none;"><p>This is my DIV element.</p></div>
    

    and this javascript

    function myFunction() {
        var x = document.getElementById("myDIV");
        if (x.style.display == "none") {
            x.style.display = "block";
        } else {
           x.style.display = "none";
          }
    }
    

    This now will work because the display none isn't by default to div element so javascript will not see the display none style and will not execute the function. So you need to specify style display none and the function will work correctly