What I want to do:
I have a navigation bar on my website. Some navigation links have sub-menus associated with them. I want to be able to hover over the navigation links that have sub-menus and have the sub-menu appear.
But, I want the sub-menu to appear differently based on the window size:
If the window is greater than or equal to 960px wide, my navigation bar is horizontal. I want the sub-menu to appear as a dropdown above the other content on the page.
If the window is less than 960px wide, my navigation bar is vertical. I want the sub-menu to appear as an accordion, pushing the other navigation links down.
I also want my script to execute when the page is done loading and when I resize the window.
My script:
function navMenu() {
if ($(window).width() >= 960) {
$('.menu-item-has-children').hover(function() {
$(this).children(".sub-menu").css('display', 'block');
}, function() {
$(this).children(".sub-menu").css('display', 'none');
});
} else {
$('.menu-item-has-children').hover(function() {
$(this).children(".sub-menu").slideToggle(500);
}, function() {
$(this).children(".sub-menu").slideUp(500);
});
}
}
$(document).ready(function() {
navMenu();
});
$(window).resize(function() {
navMenu();
});
What happens:
The above script works fine when $(document).ready() fires.
The problem lies here: If I resize the window after it has loaded, the script creates multiple mouseover and mouseout event listeners. One hover over a navigation link causes the sub-menu to bounce up and down repeatedly.
You can see what I mean here: https://codepen.io/ben393/pen/qLrMmX.
Some things I've tried (and have not worked so far):
making
.hover()a function of($(window).width() >= 960)making
$(document).ready()a function of$(window).resize()
Any ideas? Thanks!