skip to Main Content

I am trying to make a jQuery dropdown menu for mobile view. I am new to jQuery and I used Toggle to hide and show submenus. My problem is when I click one menuitem other submenu doesn’t close automatically. For example, If I click on menutwo I want menuone to close automatically. How can I do that ? 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="#"> About Us</a>
    <ul class="submenuone">
      <li>Company Overview</a>
      </li>
    </ul>
  </li>
  <li class="menutwo"><a href="#">Solutions</a>
    <ul class="submenutwo">
      <li> Receivable Finance and Collections</li>
      <li> Workers Comp Financing></li>
    </ul>
  </li>
  <li class="menuthree"><a href="#">Provider Type</a>
    <ul class="submenuthree">
      <li> Doctors</a>
      </li>
      <li> Pharmacy</a>
      </li>
    </ul>
  </li>
</ul>

2

Answers


  1. Chosen as BEST ANSWER

    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
    });
    });
    

  2. I would just use event delegation and find the other UL 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="#"> About Us</a>
        <ul class="submenuone">
          <li>Company Overview</a>
          </li>
        </ul>
      </li>
      <li class="menutwo"><a href="#">Solutions</a>
        <ul class="submenutwo">
          <li> Receivable Finance and Collections</li>
          <li> Workers Comp Financing></li>
        </ul>
      </li>
      <li class="menuthree"><a href="#">Provider Type</a>
        <ul class="submenuthree">
          <li> Doctors</a>
          </li>
          <li> Pharmacy</a>
          </li>
        </ul>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search