Why wont my navbar collapse when on mobile

Viewed 50

I'm trying to collapse the navbar when on mobile but the navbar only collapses when i resize the tab manualy. So it probably has something to do with it not checking the size of the screen when starting up the site.

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()
    
  }
    
  
}
2 Answers

You're problem is with addEventListener(). You are not listening for a state of window.matchMedia(). It should work if you use this:

var x = window.matchMedia("(max-width: 600px)")
x.addEventListener("change", () => {
    myFunction(x);
});

You should add resize event listener to your window

 window.addEventListener('resize', ()=>{
 var x = window.matchMedia("(max-width: 600px)")
 if (x.matches) { // If media query matches 
  closeNav() 
 }
 });
Related