2

The purpose of the code is to hide/show an element when the header element is clicked. Why code works and doesn't isn't clear.

Example 1

function showHideAnswers (id) {
    var x = document.getElementById(id);
    if (x.style.display === "") {
        x.style.display = "block";
    } 
}

The above code works. Notice the display if comparision of "" rather than none.

Example 2

function showHideAnswers(id) {
   var x = document.getElementById(id);
   if (x.style.display === "none") {                                                            
       x.style.display = 'block';
   } 
}

This code does not work. Notice display being compared to "none", which I think is the part that is causing it to fail; however, "none" works in example 3.

Example 3

function showHideAnswers(id) {
    var x = document.getElementById(id);
    if (x.style.display === "none") {
       x.style.display = 'block';
    } else {
       x.style.display = 'none';
    }
}

This code works, which causes me to be confused as to why example 2 doesn't work.

MacInnis
  • 760
  • 9
  • 19
  • Possible duplicate of [Can you check an object's CSS display with JavaScript?](http://stackoverflow.com/questions/4866229/can-you-check-an-objects-css-display-with-javascript) – Terry Mar 24 '17 at 11:58

3 Answers3

1

in the second example you are asking if x.style.display is equal to the string "none". the default value of display is inline so its checking if "inline" === "none". To fix the problem you must put the x.style.display to "none" before you run this code

GlacierSG
  • 469
  • 4
  • 14
1

element.style will return the value only inline style is present otherwise "" will be returned

Use Window.getComputedStyle instead!

function showHideAnswers(id) {
  var x = document.getElementById(id);
  var style = window.getComputedStyle(x, null);
  if (style.display === "none") {
    x.style.display = 'block';
  } else {
    x.style.display = 'none';
  }
}
<div id='elem'>Element</div>
<button onclick="showHideAnswers('elem')">Click me!</button>
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

In example 1, it will not work if display is already set to anything. (This will only show if display is unset, no hiding).

In example 2, you will only get action if display is explicitly set to none already. (This will only show if the element isn't already hidden, no hiding)

In example 3 you have an else clause which covers the opposite case, and so it will work for both cases (show and hide). Another reason that 3 works is because if display is unset, then the else clause will cause it to be set to none, and then block and vice-versa as you continue to call the function.

Adam Copley
  • 1,495
  • 1
  • 13
  • 31