The problem is that you are initially getting the display
property value via the style
property of the object. But, that property only returns "inline" styles applied to an element, like this:
<div style="display:none;">something</div>
Since you are setting display:none
via a separate "internal style" and not an inline style, the initial value returned from x.style.display
is an empty string, so then your code execution falls into the else
branch of your if
statement and a new inline style is then set for the element. This is why it works on the second click - - the first click actually creates an inline style where none existed before, and therefore the second click works.
You should be using window.getComputedStyle(x).display;
to get the value because .getComputedStyle()
gets a property value regardless of where or how it was set upon the element.
function myFunction() {
var x = document.getElementById("myDIV");
var displayValue = window.getComputedStyle(x).display;
if (displayValue === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#myDIV {
display:none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<p>Click the button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Click</button>
<div id="myDIV">
This is my DIV element.
</div>
Having said this, working with inline styles is generally considered a last resort because of how granular the code must get, how they lead to duplication of code, how non-scalable the code becomes and how difficult it can be to override inline styles. It is much simpler to set up CSS classes ahead of time and then apply or remove those classes to elements as needed. DOM elements support a .classList
property that provides easy ways to add, remove and toggle classes (toggle is what you want here). This approach makes the actual function code much simpler:
function myFunction() {
document.getElementById("myDIV").classList.toggle("hidden");
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
/* This class will be added, removed or toggled as needed.
It is kept separate from the element's style so that only
this property can be toggled as needed without affecting
the other styling of the element. Also, it can be used
for any other elements (as needed) that may need to be
hidden at some point. */
.hidden { display:none; }
<p>Click the button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Click</button>
<!-- Notice that the element has the class applied to it from the start
to ensure that the element is hidden from the start. -->
<div id="myDIV" class="hidden">This is my DIV element.</div>