Home > Back-end >  How to close the menu one by one when clicked again
How to close the menu one by one when clicked again

Time:01-08

I have a menu with three levels of nesting. I open each one in turn with the following code:

$(".menu-item-has-children").click(function(event) {
  event.preventDefault();
  $(this).children(".sub-menu").slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li >
  <a>About</a>
  <ul >
    <li>
      <a>Subitem1</a>
    </li>
    <li >
      <a>Subitem2</a>
      <ul >
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </li>
    <li>
      <a>Subitem3</a>
    </li>
  </ul>
</li>

The first level of nesting opens well. And when I try to open the next level, the previous one closes. And when I open it again, the next one is open. How can I fix this and make it possible to open and close the menu one by one? Menu structure

CodePudding user response:

Use event.stopPropagation(); instead of event.preventDefault();.

stopPropagation stops the current event from spreading further during the capturing and bubbling stages.

Example:

$(".menu-item-has-children").click(function(event) {
  //event.preventDefault();
  event.stopPropagation();
  $(this).children(".sub-menu").slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li >
  <a>About</a>
  <ul >
    <li>
      <a>Subitem1</a>
    </li>
    <li >
      <a>Subitem2</a>
      <ul >
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </li>
    <li>
      <a>Subitem3</a>
    </li>
  </ul>
</li>

  • Related