Recently, I've delved into the world of jQuery and attempted to create a simple menu system. The menu is designed to expand its submenu when hovering over the list item at screen widths larger than 480px, and to expand when clicking on the list item at widths less than 480px.
I thought I could utilize Modernizr's media query detection feature to enhance my code. However, my attempts have not been successful as seen in my demo here. Try hovering over the 'Properties' li tag to see the issue.
The problem seems to lie in the code's failure to recognize screen resizing properly. It functions correctly at >480px and <480px if you refresh the browser at those specific widths. But when you resize the browser, the functions still trigger incorrectly!!
Here's my code:
// Main nav dropdown animation
$(document).ready(function() {
function doneResizing() {
if(Modernizr.mq('screen and (min-width: 481px)')) {
$("#sub-menu").hide();
$("#show-investment-type-nav").hover(function() {
$(this).find("#sub-menu").stop(true, true).slideDown("fast");
}, function() {
$(this).find("#sub-menu").stop(true, true).fadeOut("fast");
});
}
else if(Modernizr.mq('screen and (max-width: 480px)')) {
$("#sub-menu").hide();
var next_move = "show";
$("#show-investment-type-nav").click(function() {
$('#sub-menu').slideToggle(100);
if (next_move === "show") {
$("body").addClass("nav-active");
$("#site-nav #icon").empty().html("");
$("#site-nav #nav-margin-down").animate({"margin-top": "163"}, 100);
next_move = "hide";
} else {
$("body").removeClass("nav-active");
$("#site-nav #icon").empty().html("");
$("#site-nav #nav-margin-down").animate({"margin-top": "0"}, 100);
next_move = "show";
}
});
}
}
var id;
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});
doneResizing();
});
If anyone can shed some light on why this glitch is happening, I'd greatly appreciate it! I'm eager to learn from my mistakes!
Thanks for your help!