Avoid Closing The Menu If Submenu Items Is Clicked
This is a multilevel menu. When i click the link 'About' it opens the submenu which contains 3 links Johnny, Julie & Jamie. When i click 'About' again, it closes the menu. Clic
Solution 1:
Alternative to stopPropagation
approach for child elements would be adding a small check if the clicked element is the current one (and not it's descendants):
$('li.parent').click(function(e) {
if (this === e.target)
$(this).find('.sub-nav').toggleClass('visible');
});
$('li.parent').click(function(e) {
if (this === e.target)
$(this).find('.sub-nav').toggleClass('visible');
});
#navul.sub-nav {
display: none;
}
#navul.visible {
display: block;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ulid="nav"><liclass="parent">About
<ulclass="sub-nav"><li><ahref="#">Johnny</a></li><li><ahref="#">Julie</a></li><li><ahref="#">Jamie</a></li></ul></li><liclass="parent">AnotherLink
<ulclass="sub-nav"><li><ahref="#">Martin</a></li><li><ahref="#">Rasmus</a></li><li><ahref="#">Morten</a></li></ul></li></ul>
Solution 2:
You need to stopPropagation
of event on child anchor elements:
$("li.parent a").click(function(e) {
e.stopPropagation();
});
Solution 3:
You need to prevent the click on the .sub-nav
element to be transmitted to your event handler: https://api.jquery.com/event.stoppropagation/
Post a Comment for "Avoid Closing The Menu If Submenu Items Is Clicked"