Skip to content Skip to sidebar Skip to footer

How Do I Make A Div Set To Style.display = "none" By Default?

I'm trying to make a button that will display additional text when it's hit, however, I can only make it either a) display the text by default or b) hide the text by default but

Solution 1:

Your handler is click. It needs to be onclick. Also, I recommend either adding a class with display:none to your div, or simply inlining it, like this:

<linkhref="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"rel="stylesheet"/><divid="myDIV"style="display: none">
 Hello World
</div><buttononclick="showInfo()">
Show Info
</button>

Then your JS can look like this:

functionshowInfo() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    return x.style.display = "block";
  }
  return x.style.display = "none";
}

Demo

functionshowInfo() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    return x.style.display = "block";
  }
  return x.style.display = "none";
}
<linkhref="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"rel="stylesheet"/><divid="myDIV"style="display: none">
     Hello World
    </div><buttononclick="showInfo()">
    Show Info
    </button>

Solution 2:

You should use CSS to set the default style for any element – either by linking to an external CSS file or in-between the opening and closing <style> tags in your HTML file.

Like so

#myDIV {
  display: none;
}

Solution 3:

There seems no issue with your JS code.

Instead

Do correct your HTML, it is 'onclick' rather than just 'click'

<buttononclick="showInfo()">

Post a Comment for "How Do I Make A Div Set To Style.display = "none" By Default?"