Close Dropdown SubMenus when closing the Dropdown Main

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><scriptsrc="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 the 3 submenu, I click the Tutorials button to close it, it closes all ... But when I click to open again, all 3 submenus are open.

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

    
asked by anonymous 11.09.2018 / 19:52

1 answer

0

I was able to do the following:

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

In Jquery I have added the following

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

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

Running on Fiddle

    
11.09.2018 / 20:05