I have a button and a div under it, the button must show this div onclick, i wrote the function and everything is fine, but it works only on second click and i can\'t figure
You have set the style in css.So the value of x.style.display
is not none initially.it wolud be empty.So set that style initially. or use getComputedStyle
to get the CSS rule
function showDiv() {
var x = document.getElementById('myDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
if the element's display is being inherited or being specified by a CSS rule, compute the style using getComputedStyle
function showDiv() {
var x = document.getElementById('myDiv');
if (getComputedStyle(x, null).display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
test
test
test
test
test
test