Skip to content Skip to sidebar Skip to footer

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');
});
#nav ul.sub-nav {
  display: none;
}
#nav ul.visible {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="nav">
  <li class="parent">About
    <ul class="sub-nav">
      <li><a href="#">Johnny</a>
      </li>
      <li><a href="#">Julie</a>
      </li>
      <li><a href="#">Jamie</a>
      </li>
    </ul>
  </li>
  <li class="parent">AnotherLink
    <ul class="sub-nav">
      <li><a href="#">Martin</a>
      </li>
      <li><a href="#">Rasmus</a>
      </li>
      <li><a href="#">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"