1

I created this function to handle the toggle for my mobile nav.

const mobileNav = document.getElementById('mobile-nav');
let tabs = document.getElementsByClassName('nav_tabs');

//nav toggle control
mobileNav.onclick = (event) => {
 event.preventDefault();
  for(let i = 0; i < tabs.length; i++) {
    if(tabs[i].style.display === "block"){
      tabs[i].style.display = "none";
    } else {
      tabs[i].style.display = "block";
    }
  }   
};

It's working on great on mobile. The problem is when I resize, the toggle is still set to display none and the toggled menu options are not visible. I have tried using this JS Media Query to reset the display block based on a min-width of 786px but it is not reseting the menu.

// media query event handler
if (matchMedia) {
const dsktp = window.matchMedia("(min-width: 768px)");
dsktp.addListener(WidthChange);
WidthChange(dsktp);
}

function WidthChange(elem) {
 for(let i = 0; i < elem.length; i++) {
  tabs[i].style.display = "block";
 } 
}

Here's a codepen of the problem.

TYPOI
  • 361
  • 2
  • 6
  • 19

1 Answers1

1

Your code does not work because of this code (pay attention to the comments):

if (matchMedia) {
  const dsktp = window.matchMedia("(min-width: 768px)");
  dsktp.addListener(WidthChange); // <-- add function as handler
  WidthChange(dsktp);
}

function WidthChange(elem) { // elem argument it is not the dom elements here
  for(let i = 0; i < elem.length; i++) {
    tabs[i].style.display = "block";
  } 
}

So you should rewrite your code this way:

if (matchMedia) {
  const dsktp = window.matchMedia("(min-width: 768px)");
  dsktp.addListener(WidthChange);
  WidthChange(dsktp);
}

function WidthChange(mediaQueryEvent) {
  for(let i = 0; i < tabs.length; i++) {
    tabs[i].style.display = mediaQueryEvent.matches ? "block" : "none";
  } 
}

Check my fork of your pen.

Mikhail Shabrikov
  • 8,453
  • 1
  • 28
  • 35
  • So that totally works to correct the display on larger sizes but it also gives me the opposite problem of the menu being open by default on mobile. The default behavior should be display none on mobile(less than 786) and display block on anything larger... – TYPOI Nov 18 '17 at 00:06
  • @TYPOI Oh, I did not notice it. I fixed it now and updated the answer and the pen, check, please. – Mikhail Shabrikov Nov 18 '17 at 00:09
  • @TYPOI Check now, please. Is it what you need? – Mikhail Shabrikov Nov 18 '17 at 00:16
  • Yes, thank you Mikhail!!! That's perfect! So if I understand what you did - the default width change is set to false and the media query matches the width using the ternary - block for true, none for false... – TYPOI Nov 18 '17 at 00:22
  • You are welcome! I have done some refactoring for my pen and decrease the amount of code a bit. It is the final version. – Mikhail Shabrikov Nov 18 '17 at 00:35