How to close other submenus onclick jquery

I have this multiple level menu code as shown below. When one of the menus is open up and i want to click on 2nd menu the old submenu is not being close automatically.

for example, I click on "New dropdown" the test1ddm will open up. and when i click on "Drop down 2" the test1ddm is not close but being stack behind test2ddm.

How do i make it closeable when clicking on other menus?

 <div class="container">                                      
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorials
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li class="dropdown-submenu">
        <a class="test" id="test1" tabindex="-1" href="#">New dropdown <span class="caret"></span></a>
        <ul class="dropdown-menu" id="test1ddm">
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
        </ul>
      </li>
      <li class="dropdown-submenu">
        <a class="test" id="test2" tabindex="-1" href="#">Drop down 2 <span class="caret"></span></a>
        <ul class="dropdown-menu" id="test2ddm">
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>        
        </ul>
      </li>
    </ul>
  </div>
</div>

Scripts

<script>
  $(document).ready(function(){
    $('.dropdown-submenu a.test').on("click", function(e){
      $(this).next('ul').toggle();
      e.stopPropagation();
      e.preventDefault();
    });
  });
</script>

Answers 1

  • You might want to do this with CSS, but if you are intent on JS, the following should work:

    $(document).ready(function(){
      $('.dropdown-submenu a.test').on("click", function(e){
        $(this).parent().parent().find('.dropdown-menu').hide();
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });
    });
    

    Before opening any item in a menu, it first closes all items in the same menu, and then open the one you selected. It should also work for multiple levels (but for that you'll have to modify your selector).


Related Articles