Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide Elements in Javascript

I want that the text ist hidden in the beginning and after clicking the button it is displayed. I would be really greatfull if someone would find the mistake in my code.

function F1()
{
  var x = document.getElementById("step1DIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<!DOCTYPE html>
<html>

<body>

  <button onclick="F1()"> <b>Step 1</b> </button>
  <div id="step1DIV">
    <p> text </p>
  </div>

</body>

</html>
like image 990
Save Pain Avatar asked Nov 27 '25 11:11

Save Pain


1 Answers

You need to give it an initial style that hides it in the HTML.

function F1()
{
  var x = document.getElementById("step1DIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
  <button onclick="F1()"> <b>Step 1</b> </button>
  <div id="step1DIV" style="display: none;">
    <p> text </p>
  </div>

But inline styles are poor design, it's better to use a class with CSS.

function F1()
{
  var x = document.getElementById("step1DIV");
  x.classList.toggle("hidden");
}
.hidden {
  display: none;
}
<button onclick="F1()"> <b>Step 1</b> </button>
  <div id="step1DIV" class="hidden">
    <p> text </p>
  </div>
like image 174
Barmar Avatar answered Nov 29 '25 01:11

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!