Responsive conflict between Javascript and @media?

I try to hide/show a vertical nav. Both when resizing and by a hamburger icon. The odd is that each routine works as expected when used one by one. But once triggered the Javascript, the @media stops working.

The Javascript:

<script>
      function toggle() {
        var n = document.getElementById("nav");
        var c = document.getElementById("content");
        if (n.style.display === "none") {
          n.style.display = "block ";
          c.style.gridColumn = "2/3";
        } else {
          n.style.display = "none";
          c.style.gridColumn = "1/3"
        }
      }
    </script>

and the css @media:

@media only screen and (max-width: 880px) {
.grid {
  grid-template-columns: max-content;
  } 
.nav {
  display: none;
  }
}

Live: http://94.237.25.207:8080/home

What am I doing wrong?

Your javascript modifies inline style.
With your javascript, add/remove css class instead. Like that, the mediaqueries work.

Sounds good. Any tip or link how to do this?

el.classList.add(‘myClass’);
el.classList.remove(‘myClass’);

Well, it does not work ( I do not know the syntax) :

However this works javascript OR @media (until I click on the button):

Any help appreciated.

you have to give the class name to add or remove.

el.classList.add('className’);
el.classList.remove(‘className’);

Still does not work:

  function toggle() {
    var n = document.getElementByClassName("nav");
    if (n.style.width === "0px") {
      n.classList.remove("nav");
    } else {
      n.classList.add("nav");
    }
  }

For example: https://jsfiddle.net/YiuJia/3nyxhjbk/2/

i dont look mediiaqueries.

What do you mean with “i dont look mediiaqueries”? It does not work with @media queries. The nav menu should disappear on small devices.

@media only screen and (min-width: 501px) {
.grid {
    grid-template-columns: max-content;
  }

  .nav {
    display: block;
  }
}
@media only screen and (min-width: 501px) {
.grid {
    grid-template-columns: max-content;
  }

  #nav {
    display: block;
  }
}

you should target the #nav instead i think.

getElementByClassName is not a valid method.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.