Question

I'm building my first responsive menu. and I got everything working pretty well, but there is 1 ting I cant get fixed.

I have a menu. and when the width of the page gets smaller than 600 px it changes to a drop down menu. Now I have the following problem:

when my menu is in dropdown mode (screen size < 600) it it has to collapse as soon as you pick a menu item. I used this code to archieve this:

//check if the screen size < 600. if yes let menu hide on click.
if (window.innerWidth < 600) {// this is the code that gives me trouble
$( "#top-menu" ).click(function() {
       $( "#top-menu" ).hide();
      });
}

//toggle the menu when in small screen size. 

$( "#pull" ).click(function() {
$( "#top-menu" ).toggle();

});

demo (not clean but good enough to show you what I mean): http://jsfiddle.net/skunheal/r4tdm/

this works fine when I start in a screen <600 px. But as soon as I scale up the browser to lets say 800 pixels it still hides the menu on click. While My code says if (window.innerWidth < 600) {

if I refresh my page at 800px it wont ever hide my menu if I scale it down to <600 px.

My conclusion is that window.innerWidth doesnt update itself when resizing the browser window. anybody has a suggestion?

Was it helpful?

Solution

You have to add an event onresize to check , it will not check on resize of window with out any event listiner

 window.addEventListener('onresize',function(){  

      if (window.innerWidth < 600) {           
           $( "#top-menu" ).hide(); //i think you just need this only        
      } else {
           $( "#top-menu" ).show();
      }

  })

OTHER TIPS

change your code to this :

//check if the screen size < 600. if yes let menu hide on click.
if (window.innerWidth < 600) {// this is the code that gives me trouble
$( "#top-menu" ).click(function() {
       $( "#top-menu" ).hide();
      });
}else if (window.innerWidth > 600){
    $( "#top-menu" ).click(function() {
     $( "#top-menu" ).show();
      });

}

//toggle the menu when in small screen size. 

$( "#pull" ).click(function() {
$( "#top-menu" ).toggle();

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top