I am currently in the process of coding my navbar for the mobile viewport. I did some searching and I thought I had a solution, but it turns out the solution isn’t working at all. I’m trying to make it so that when the nav burger in the navbar is clicked/ tapped, the navigation options slide in to the screen from right to left. I’m not sure where the logical error is, or why the nav burger being clicked isn’t responding to the event.
Here is the HTML corresponding to the nav burger:
<div id="nav-burger"> <div id="option-1"></div> <div id="option-2"></div> <div id="option-3"></div> </div>
Here is the relevant CSS (note: nowhere in my HTML do I have an element with a class of ‘nav-active’ – in case this is relevant):
#nav-title a { flex: 1; text-align: center; line-height: 2.5; } #nav-links { display: flex; flex-direction: column; align-items: center; justify-content: space-evenly; background-color: #404040; position: absolute; top: 40px; height: 40vh; width: 100%; transform: translateX(100%); transition: transform 1s ease-in; } .nav-active { transform: translateX(0%); }
And lastly, here’s the JS code I have so far:
const navSlider = function() { const navBurger = document.querySelector('#nav-burger'); const nav = document.querySelector('#nav-links'); navBurger.addEventListener('click', function() { nav.classList.toggle('nav-active'); }); } navSlider();
Advertisement
Answer
Hello potential viewers of the question, I managed to solve my own problem. It seems like the JS needed filled out a little bit, and when I made these changes I got the script to work:
const navSlider = function() { const navBurger = document.querySelector('#nav-burger'); let nav = document.querySelector('#nav-links'); navBurger.addEventListener('click', function() { nav.classList.toggle('nav-active'); document.getElementById('nav-links').style.transition = "transform 0.9s ease-in"; if (nav.getAttribute('class') === 'nav-active') { nav.style.transform = 'translateX(0%)'; } else { nav.style.transform = 'translateX(100%)'; } }); } navSlider();
I came across this solution rather serendipitously. When working on some other things for mobile view, I noticed that when I went from full screen and made the window smaller to something close to mobile view, the nav options would appear and slide off the screen, as directed to do by the translateX CSS properties inside the question’s CSS. This got me thinking about what the CSS properties were doing, and how they might actually better be placed inside the JS. A few changes later, and I have a working navbar slider for mobile view! Here’s what the relevant CSS looks like now:
#nav-title a { flex: 1; text-align: center; line-height: 2.5; } #nav-links { display: flex; flex-direction: column; padding-left: 20%; justify-content: space-evenly; background-color: #404040; border: 1px solid #a1a9fe; position: absolute; top: 40px; height: 40vh; width: 100%; transform: translateX(100%); }