Thanks for updating the Fiddle example, the problem is that there is a conflict between the visual changes performed by CSS and jQuery. In addition, there is no code that would not force the mobile menu to hide after changing the screen size to the desktop.
The solution I came across is to first configure CSS to satisfy the basic visual changes for each media query , and then do the same for jQuery changes using a listener that checks for screen width changes.
Here is the fiddle of this in action
CSS
If scripts are disabled, your CSS should always handle the basics of what you want to achieve. Otherwise, the page may break. It also has the huge benefit of less page load (never use JS when CSS can handle it).
You need to clearly indicate what should happen to any mobile / non-mobile element, if you change it at all using media queries. Given that we are talking about something that has states: showing/hidden , you should indicate what these states refer to:
For your mobile layout:
@media all and (max-width:630px) { #menu { display:none; } #m_menu { display:block; } #m_btn{ display:inline-block; } }
Desktop layout
In principle, undo everything you have done for the mobile version:
@media all and (min-width:631px) { #m_menu { display:none; } #menu{ display:block; } #m_btn{ display:none; } }
Alternatively, you can completely remove the media query around the desktop styles, since any styles specified outside (max-width:630px) will be applied regardless of whether the value 630px is exceeded.
JQuery
You can then use the listener to check when the width changes after the checkpoint you have selected. It’s hard to grab the exact width since “630” shot too wide, so I went with 617 when it compared the media query breakpoints.
Please note that this only applies to changing the screen size, i.e. the user drags his browser size or changes the orientation of his device from portrait to landscape or vice versa.
Inside the if , which will only work when the screen is resized to the size of the desktop, we can forcibly hide #m_menu .
$(window).resize(function() { // Detect if the resized screen is mobile or desktop width if($(window).width() > 617) { console.log('desktop'); $('#m_menu').sidebar('hide'); } else { console.log('mobile'); } });
Probably the best way to do this last part, since .resize() can fire many times per second and can noticeably slow down the page.
In my experience of creating sensitive sites, it’s very useful to have a fragment of “conditional javascript” that is specially configured for this kind of script, which behaves the same as media queries .