search

Home  >  Q&A  >  body text

The rewritten title is: How to implement automatic closing of submenu in jQuery

I'm trying to create a jQuery dropdown menu for a mobile view. I'm new to jQuery and I'm using Toggle to hide and show submenus. My problem is that when I click on a menu item, the other submenus don't close automatically. For example, if I click menutwo, I want menuone to close automatically. How can I do this? please help.

jQuery(document).ready(function($) {
  $(".menuone").click(function() {
    $(".submenuone").toggle(200);
  });
  $(".menutwo").click(function() {
    $(".submenutwo").toggle(200);
  });
  $(".menuthree").click(function() {
    $(".submenuthree").toggle(200);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu-menu" class="menu dropdown-menu">
  <li class="menuone"><a href="#">关于我们</a>
    <ul class="submenuone">
      <li>公司概况</a>
      </li>
    </ul>
  </li>
  <li class="menutwo"><a href="#">解决方案</a>
    <ul class="submenutwo">
      <li>应收账款融资和催收</li>
      <li>工人补偿融资></li>
    </ul>
  </li>
  <li class="menuthree"><a href="#">提供者类型</a>
    <ul class="submenuthree">
      <li>医生</a>
      </li>
      <li>药房</a>
      </li>
    </ul>
  </li>
</ul>

P粉312631645P粉312631645437 days ago1089

reply all(2)I'll reply

  • P粉207483087

    P粉2074830872023-09-17 00:28:15

    Made it finally.

    Here is my answer

    jQuery(document).ready(function($) {
      $(".menuone").click(function() {
      $(".submenuone").toggle(200);
      $(".submenutwo, .submenuthree").hide(200); // Hide other submenus
      });
    
    $(".menutwo").click(function() {
    $(".submenutwo").toggle(200);
    $(".submenuone, .submenuthree").hide(200); // Hide other submenus
    });
    
    $(".menuthree").click(function() {
    $(".submenuthree").toggle(200);
    $(".submenuone, .submenutwo").hide(200); // Hide other submenus
    });
    });

    reply
    0
  • P粉146080556

    P粉1460805562023-09-17 00:17:27

    I would use event delegation and find other ULs and close them.

    jQuery(document).ready(function($) {
      $("#menu-menu").on("click", "> li", function () {
         $("#menu-menu > li").not(this).find("ul").hide(200);
         $(this).find("ul").toggle(200);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul id="menu-menu" class="menu dropdown-menu">
      <li class="menuone"><a href="#">关于我们</a>
        <ul class="submenuone">
          <li>公司概况</a>
          </li>
        </ul>
      </li>
      <li class="menutwo"><a href="#">解决方案</a>
        <ul class="submenutwo">
          <li>应收账款融资和催收</li>
          <li>工人赔偿融资></li>
        </ul>
      </li>
      <li class="menuthree"><a href="#">供应商类型</a>
        <ul class="submenuthree">
          <li>医生</a>
          </li>
          <li>药房</a>
          </li>
        </ul>
      </li>
    </ul>

    reply
    0
  • Cancelreply