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
Setting CSS style does not pervade to x.style.display
so when you click the first time x.style.display
actually equals ""
, so it hits your else block and sets the style.display
to none
, 2nd time and it hits the first branch of the conditional and shows your div.
Either use computedStyle
to grab the actual style, or, this would be a little easier using classes.
JS:
function show () {
var x = document.querySelector('#myDiv')
x.classList.toggle('show')
}
CSS:
.show {
display: 'block';
}
Classlist
is supported for all modern browsers but some really old ones will struggle with it, although good polyfills exist.