Forgive me if this is a silly question, but I'm having trouble. I need a slide-in navigation menu for smaller screens that is triggered by JavaScript. Here is what I currently have:
HTML
<nav class="responsive">
<ul class="nav-list unstyled">
<li class="nav-item"><a href="#">Shop</a></li>
<li class="nav-item"><a href="#">Our Story</a></li>
<li class="nav-item"><a href="#">Information</a></li>
<li class="nav-item"><a href="#">Magazine</a></li>
<li class="nav-item"><a href="#">Contact</a></li>
</ul>
</nav>
SCSS
nav.responsive {
ul {
text-align: center;
list-style-type: none;
padding: 0;
margin: 0;
display: none;
transform: translateX(-100%);
background-color: #fafafa;
li {
a {
display: block;
padding: 12px;
border-bottom: 1px solid #dadada;
}
}
&.menu-list-active {
display: block;
animation: slide-in 0.5s forwards;
}
}
@media only screen and (min-width: 720px) {
ul {
display: block;
transform: none;
li {
display: inline-block;
a {
border-bottom: none;
}
}
}
}
div.nav-mobile {
display: block;
height: 48px;
width: 48px;
position: absolute;
top: 0;
right: 0;
background-color: #999999;
cursor: pointer;
&.menu-button-active {
background-color: #555555;
}
@media only screen and (min-width: 720px) {
display: none;
}
}
}
@keyframes slide-in {
100% { transform: translateX(0); }
}
Javascript
// Create the mobile navigation toggle button
var mobile = document.createElement('div');
mobile.className = 'nav-mobile';
document.querySelector('nav.responsive').appendChild(mobile);
// Set some variables
var mobileNav = document.querySelector('.nav-mobile');
var navList = document.querySelector('.nav-list');
// Handle showing the menu
mobileNav.onclick = function () {
this.classList.toggle('menu-button-active');
navList.classList.toggle('menu-list-active');
};
The current setup is functioning as intended, with the menu sliding in nicely. However, I also want it to slide out when the nav-mobile
button is clicked. I attempted animating the ul
initially, but that caused the menu to slide out when the screen size was reduced, which is not desired. Ideally, the menu should be hidden when the page loads on a small screen.
Is there a way to achieve this functionality?
EDIT
Check out the Codepen here: