Home > Back-end >  How can I show a hidden text by clicking on a button?
How can I show a hidden text by clicking on a button?

Time:10-24

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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!

CodePudding user response:

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

CodePudding user response:

= is assignment. == and === are comparison. So inside of the if, change it to one of those two.

You also didn't properly close the <div> in the code you submitted.

Another thing is that you're setting the display: none in a CSS file. JavaScript doesn't have access to this value, it only has access to style="..." in the HTML markup of the element. To fix this issue, check if it's not hidden and swap around the sides of the if/else block.

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display == "block") { // `=` to `==` or `===`
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
#myDIV {
  display: none;
}
<ul>
  <li><button onclick="myFunction()">Try it</button>
    <div id="myDIV">
      <p>This is my DIV element.</p>
    </div> <!-- this div wasn't closed properly -->
  </li>
</ul>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

function myFunction() {
  var x = document.getElementById("myDIV");
  x.style.display = x.style.display != "block"?"block":"none"
}
#myDIV{ display: none; } 
<ul>
  <li><button onclick="myFunction()">Try it</button>
    <div id="myDIV"><p>This is my DIV element.</p></div 
  </li>
</ul>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related