I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 700px, the submenus will be triggered onHover.
The window resize code is in place to facilitate changes when resizing the window without needing to refresh the page. It functions correctly, but the problem arises when clicking/hovering on any of the two links with nested sub-lists; it opens ALL the nested lists instead of just the one clicked on. Apart from this issue, everything else works as intended.
Here is the HTML code (with the .navLevel2 class having display: none):
<div class="mainNav">
<ul class="navLevel1">
<li><a href="">link 1</a></li>
<li class="fakeLink">link 2
<ul class="navLevel2">
<li><a href="">link 2.1</a></li>
<li><a href="">link 2.2</a></li>
</ul>
</li>
<li class="fakeLink">link 3
<ul class="navLevel2">
<li><a href="">link 3.1</a></li>
<li><a href="">link 3.2</a></li>
</ul>
</li>
<li><a href="">link 4</a></li>
</ul>
</div>
And here is the jQuery code:
<script>
$(document).ready(function(){
function checkWidth() {
var windowsize = $(window).width();
if (windowsize < 700) {
$('.navLevel1').addClass('small');
$('.fakeLink').attr('onclick','return click_m()');
} else {
$('.navLevel1').addClass('big');
$('.fakeLink').attr('onmouseover','return toggle_m()').attr('onmouseout','return toggle_m()');
}
}
checkWidth(); // Execute on load
$(window).resize(function() {
if($(window).width() < 700) {
$('.mainNav > ul').removeClass('big');
$('.mainNav > ul').addClass('small');
$('.fakeLink').attr('onclick','return click_m()');
$('.fakeLink').removeAttr('onmouseover','return toggle_m()').removeAttr('onmouseout','return toggle_m()');
}
else if($(window).width() > 700) {
$('.mainNav > ul').removeClass('small');
$('.mainNav > ul').addClass('big');
$('.fakeLink').attr('onmouseover','return toggle_m()').attr('onmouseout','return toggle_m()');
$('.fakeLink').removeAttr('onclick','return click_m()');
}
}) // window.resize
}) // document.ready
</script>
The triggers defined in the header:
function click_m(){
$('.fakeLink > ul').slideToggle(300);
}
function toggle_m(){
$('.fakeLink > ul').stop().slideToggle(300);
}
My issue now is: When hovering/clicking on Link 2 or Link 3, it opens ALL the nested lists simultaneously. I am struggling to identify the root cause of this bug. Your help would be greatly appreciated!
Thank you!