0

When we style a div with an inline display: none and then try to toggle it using style.display = 'block' it works as expected.

However, when we style a div with display: none set in CSS and then try to toggle it, it skips one turn (presumably because it sets the display property inline) before working as expected.

What is the right way to change display for divs set in CSS?

As an example of the behaviour I'm talking about, consider the following snippets:

document.getElementById("toggle").addEventListener("click", function() {
  var elt = [];
  elt.push(document.getElementById("inlineStyle"));
  elt.push(document.getElementById("cssStyle"));

  elt.forEach(function(e) {
    e.style.display = e.style.display === 'none' ? 'block' : 'none';
  });
});
#cssStyle {
  display: none;
}
<button id="toggle">Toggle</button>
<div id="inlineStyle" style="display: none">
  <p>Inline styling</p>
</div>
<div id="cssStyle">
  <p>CSS styling</p>
</div>

Then, when we click on the toggle button, the divs appear alternately instead of together.

Barmar
  • 741,623
  • 53
  • 500
  • 612
sntx
  • 45
  • 7
  • 1
    That's because you can't read styles set by the stylesheet via element.style - go research it please, this has been discussed a lot already. – CBroe Aug 08 '16 at 21:42

1 Answers1

0

The thing here is that element.style is not corresponding to styling done with CSS, but set via style="" directly. So your element with id inlineStyle has a value for style.display, but the element with id cssStyle does not.

And it is this value you are checking in your click handler, and so this is why you see different results. If you would change the logic in the forEach to

e.style.display = e.style.display !== 'block'? 'block' : 'none';

They wil behave the same

0xRm
  • 1,259
  • 8
  • 11