I'm trying to do a toggle button with js, but the first time it's clicked it is not working. Since the nav.display.display
has no value although it has display: none;
in the CSS code.
I guess there should be an issue on how I'm using onload... as if the css wasn't loaded yet. But I've read that window.onload
waits for all to load. So I don't really know what's happening.
This is how I'm loading it, in real code (outside jsfiddle that handles onload)
window.onload = function() {
var el = document.querySelector('.nav-toggle');
el.addEventListener("click", toggleNav, false);
};
NO jQuery please.
Here's the jsfiddle:
function toggleNav() {
var nav = document.querySelector('#navigation');
alert(nav.style.display);
if (nav.style.display == 'none') {
nav.style.display = 'flex';
} else {
nav.style.display = 'none';
}
}
var el = document.querySelector('.nav-toggle');
el.addEventListener("click", toggleNav, false);
#navigation {
display: none;
}
<button class="nav-toggle">Toggle</button>
<nav id="navigation">
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
<li><a href="#">Item 5</a></li>
</ul>
</nav>