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

I already check all over the internet yet I can't figure it out. Every time it loads I have to click it twice in order to show the element. I also tried to replace

else {
   ​x.style.display = "none";

none to block. it works but doesn't go back. I hope you guys can help me Thank you in advance

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
  • Can you provide the entire JavaScript code or preferably the part where you're invoking `myFunction` ? – Siddhant Varma Jun 29 '21 at 04:12
  • 1
    Your `if` statement is useless. – enzo Jun 29 '21 at 04:16
  • Checking CSS properties directly is [best avoided](/q/55071684/4642212). Instead, a CSS class should be used, e.g. `.cls { display: none; }`; then [`.classList.has("cls")`](//developer.mozilla.org/en-US/docs/Web/API/Element/classList) to check for its existence, `.classList.toggle("cls", condition)` for setting the class iff `condition` is true, etc. Consider using the [`hidden` attribute](//developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) instead. – Sebastian Simon Jun 29 '21 at 05:26

3 Answers3

0

What if we do this:

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

And also please share you html too

Blaze_droid
  • 479
  • 4
  • 13
0

The issue that you are facing is the styling between css styling and inline styling. If the display of yor element is controlled by css class initially, the value of x.style.display will be an empty string. So that x.style.display === "none" will be false and your else block will execute that will set x.style.display = "none" and now when you execute the function x.style.display is none hence your if block executes and the display will be set to block. That's why it works on second click.

Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

The problem is that you are comparing an empty string in the if statement. You can either set the display to none property via JS instead of CSS or modify your if statement. So, this should do the work

if (x.style.display === "none" || x.style.display === "")

But I strongly recommend you to try some other logic/method.