Arman Haque Arman Haque - 6 months ago 19
HTML Question

JS - Window width function not working

So I have a responsive navigation menu.
a button is used to toggle the menu in and out. This is working fine.

I added an exception, where if the window exceeds a certain width, the menu closes, however this is not working at all. I can't find what is wrong with this code.

JS:

$(document).ready(function(){
$(".menubutton").click(function(){
$(".respmenu-gen").toggleClass("respmenu-opn respmenu-cls");
});
if ($(window).width() > 767) {
$(".respmenu-gen").removeClass("respmenu-opn").addClass("respmenu-cls")
};
});


jsfiddle:
https://jsfiddle.net/76amgsb8/

Thank you!

Answer

You should use the window.resize() method. Check it out here.

What you essentially do here is when content loads you check the width of window, just once. You should be bound on the resize event.

So, you can essentially do the following:

$( window ).resize(function() {
  var viewportWidth = $(window).width();
  if (viewportWidth > 767)
      $(".respmenu-gen").removeClass("respmenu-opn").addClass("respmenu-cls")
});

$(document).ready(function(){
    $(".menubutton").click(function(){
        $(".respmenu-gen").toggleClass("respmenu-opn respmenu-cls");
    });
});

If you are bound to work with JavaScript about responsiveness, I would suggest to use the window.matchMedia(mediaQueryString) way though, as relying on jQuery resize() won't give you exact results. window.matchMedia() is more powerfull and you can also benefit from familiar CSS3 media queries. https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

Comments