Currently, I am in the process of designing a responsive navigation system which involves implementing a button that dynamically changes the styling of the div #navigation using Javascript. The aim is to toggle between display: none;
and display: block;
based on user interaction.
Everything seems to be working as intended when viewed on small screens. However, an issue arises when I show and hide the navigation on a small screen, then resize the window – the navigation remains hidden.
Is there a way to automatically adjust the CSS based on window size?
Below you can find the code snippet that I am currently utilizing (please note that I am new to Javascript): Feel free to experiment by resizing the window, opening and closing the navigation, and resizing again. You will notice that the navigation remains hidden: http://codepen.io/HannesDev/pen/grjdqK
HTML:
<div class="btn-Nav">Navigation</div>
<nav id="nav-hor" role="navigation">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</nav><!-- #site-navigation -->
CSS:
html{
background: lime;
}
/* The Button */
.btn-Nav{
border: 2px solid grey;
cursor: pointer;
}
/* The button changes to the greyed out closed area on the right */
.btn-Nav_open{
position: fixed;
margin-left: 80vw;
left: 0;
top: 0;
width: 20vw;
height: 100vh;
background-color: black;
color: white;
opacity: .2;
padding: .2em;
text-align: center;
font-size: 3em;
}
/* The Navigation on small screens */
#nav-hor{
display: none;
position: fixed;
overflow-y: scroll;
top: 0;
width: 80vw;
height: 100vh;
background-color: white;
z-index: 999;
border-right: 1px solid grey
}
@media (min-width: 50em) {
html{
background: red;
}
/* Don't show the button on bigger screens */
.btn-Nav{
display: none;
}
/* The Navigation for bigger screens */
#nav-hor {
/* Clean up */
display: flex;
position: relative;
overflow: visible;
width: 100%;
height: auto;
}
JS:
window.onload = function(){
document.querySelector('.btn-Nav').onclick = function(){
// closed
if(this.className.match('btn-Nav btn-Nav_open')) {
this.className = 'btn-Nav';
document.getElementsByClassName("btn-Nav")[0].innerHTML = "Navigation";
document.getElementById('nav-hor').style.display = "none";
document.body.style.overflow = "auto";
}
// open
else {
this.className = 'btn-Nav btn-Nav_open';
document.getElementsByClassName("btn-Nav")[0].innerHTML = "×";
document.getElementById('nav-hor').style.display = "block";
document.body.style.overflow = "hidden";
}
};
};