Close Dropdown submenus when closing the Main Dropdown

Asked

Viewed 149 times

0

$(document).ready(function(){
  $('.dropdown-submenu a.sub').on("click", function(e){
    $(this).next('ul').toggle();
    e.stopPropagation();
    e.preventDefault();
  });
});
.dropdown-submenu {
    position: relative;
}

.dropdown-submenu .dropdown-menu {
    top: 0;
    left: 100%;
    margin-top: -1px;
}
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <h2>Multi-Level Dropdowns</h2>
  <p>In this example, we have created a .dropdown-submenu class for multi-level dropdowns (see style section above).</p>
  <p>Note that we have added jQuery to open the multi-level dropdown on click (see script section below).</p>                                        
  <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><a tabindex="-1" href="#">HTML</a></li>
      <li><a tabindex="-1" href="#">CSS</a></li>
      <li class="dropdown-submenu">
        <a class="sub" tabindex="-1" href="#">New dropdown <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
          <li class="dropdown-submenu">
            <a class="sub" href="#">Another dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">3rd level dropdown</a></li>
              <li><a href="#">3rd level dropdown</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

With this example of Dropdown, when I open up to the 3 submenu, I click on the Tutorials to close it, it closes all... However, when I click to open again, all 3 submenus are open.

How can I close all submenus when I close the dropdown?

1 answer

0

I was able to do it this way:

In my <ul class="dropdown-menu">, apart from the main, I added the child class: <ul class="dropdown-menu filho"> and on my main dropdown button <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" id="pai"> added the id="pai".

In Jquery I added the following

$('#pai').on("click", function(){ $('.filho').hide(); });

So every time I click on the menu it hides the menus that were eventually open.

Functioning in the Fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.