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.