I have this code which shows/hides a menu when a button is cicked
$('#main-menu ul').slideToggle();
the menu is hidden when the browser window is less than 767 px, so this button appears which allows it to be toggled on and off, this works except the only problem is when I resize the window bigger again, the menu is gone, if slide toggled has set it to display none. to fix this I added code to show the menu once the browser resizes. this then causes the new menu to show, when the browser window is scaled down again less than 767 px, instead of having the default be hidden. I can then hide the menu again when scaled less than 767px but this causes a flash of the menu as it is hidden.
I was wondering a way to detect if resize() was scaling up r down in this case when scaling down I can hide() menu and when scaling up I can show() menu.
$('.menu-button').click(function() {
$('#main-menu ul').slideToggle();
});
$(window).resize(function(){
var w = $(window).width();
if(w > 767 && $('#main-menu ul').is(':hidden')) {
$('#main-menu ul').show();
}
});
$(window).resize(function(){
var w = $(window).width();
if(w < 767) {
$('#main-menu ul').hide();
}
});
You’ll need to store the previous dimensions and decide whether the resize is increasing or decreasing in size based on that.
To keep the menu visible when the browser window is resized and the user’s chosen to display it, you’ll just need to store a flag stating that the user chose to make it visible:
(Note that with this technique, the code block that determines if the window got bigger or smaller is completely unnecessary)