jQuery dropdown menu causes infinite loop after page resize
I've attempted to create a navigation menu for a website which is a normal
horizontal navigation bar on large screen widths, but becomes a jQuery
dropdown when the window width is below 980px.
If the initial page load occurs with the window at less than 980px, the
menu works as expected. However, if the window is resized at all, the
mobile menu opens and closes multiple times before finally opening fully.
The website is http://host26.qnop.net/~fpsl/ - if you load it full-screen
on a desktop computer, resize the window to a small width, and click the
green button on the top right, you will see the behaviour of the menu.
My code is as follows:
jQuery(document).ready(function($) {
if($(window).width() < 980) {
$("#mmenu").hide();
$(".mtoggle").click(function() {
$("#mmenu").slideToggle(500);
});
}
});
// check for window resize - show nav again for larger screens after
hiding
$(window).resize(function() {
if($(window).width() < 980) {
$("#mmenu").hide();
$(".mtoggle").click(function() {
$("#mmenu").slideToggle(500);
});
}
if ($(window).width() > 980) {
$('#mmenu').show();
}
});
I am very much a jQuery beginner and assume something I have done in the
second section of the code is creating a loop somehow, but I don't know
why or what I can do to correct it - I've tried changing the declarations
to an if/else format but this makes no difference. I also don't understand
why, if an accidental loop is occurring, the behaviour stops after a few
opens and closes rather than continuing infinitely.
Any help would be much appreciated!
No comments:
Post a Comment