I'm having trouble collapsing the navbar on mobile devices. Currently, the navbar only collapses when I manually resize the tab. It seems like the issue is related to it not checking the screen size when the site initially loads. I've attempted to use addeventlisteners but keep encountering errors due to unexpected tokens. The original code I had was:
function openNav() {
document.getElementById("mySidebar").style.width = "190px";
document.getElementById("main").style.marginLeft = "190px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
}
var x = window.matchMedia("(max-width: 600px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
function myFunction(x) {
if (x.matches) { // If media query matches
closeNav()
}
}
After seeking help from others, I decided to experiment with this:
var x = window.matchMedia("(max-width: 600px)")
x.addEventListener("change", () => {
myFunction(x);
});
and
window.addEventListener('resize', ()=>{
var x = window.matchMedia("(max-width: 600px)")
if (x.matches) { // If media query matches
closeNav()
}
});
I've been up for hours trying to solve this, and I know it's probably something simple that I'm missing.