user2607925
user2607925

Reputation: 103

Need to click twice to display a div after loading the page

My code is very simple. But I can't figure out the problem. The problem is after the page is loaded/refreshed, I need to click hyperlink twice to display a div. But once the div is displayed, I only need to click once to display/undisplay.Please help! Why the first time I need to click twice? Thanks!!

 function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
      x.style.display = "block";
  } else {
      x.style.display = "none";
  }
}
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
  display: none;
 }
<a href="javascript:myFunction()" style="color="#0000FF"">click to display:</a> 
<div id="myDIV">
  display text area
</div>

I tried different ways, one is <a href="" onClick="myFunction();return false;">click here</a>

Upvotes: 4

Views: 441

Answers (2)

Caleb H.
Caleb H.

Reputation: 1717

The x.style.display property has no value at the start of the code. To fix it, simply put this line right before your function definition, to give the property a preset value:

document.getElementById("myDIV").style.display = "none";

That should fix it for you

Upvotes: 3

31piy
31piy

Reputation: 23859

CSS style rules aren't exposed to JavaScript. You need to use getComputedStyle to get the CSS rendered style values in JavaScript.

Change your code to this:

if (window.getComputedStyle(x).display === "none") {
    x.style.display = "block";
} else {
    x.style.display = "none";
}

Check-out the working snippet below:

<html>
<head>
  <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
      display: none;
    }
  </style>
</head>

<body><br>
  <font color="#0000FF"><a href="javascript:myFunction()">click to display:</a>
  </font>
  <div id="myDIV">
    display text area
  </div>
  <script>
    function myFunction() {
      var x = document.getElementById("myDIV");
      
      if (window.getComputedStyle(x).display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>
</body>

</html>

Upvotes: 2

Related Questions