How can the Multi-tiered Dropdown Menu be Enhanced?

I am in search of creating a multi-level accordion menu. I have developed this menu ( http://codepen.io/anon/pen/ogdovx ) until now but I am fairly new to jquery and feeling stuck when it comes to advancing it further.

How can I enhance this? My requirement is for it to display only the items with sub UL's and collapse siblings/children when opened.

Any guidance on enhancing my code would be highly appreciated. Thanks!

Code snippet from codepen:

$(document).ready(function() {

   $(".main > li > a").click(function() {
      $('.main ul').slideUp();
      if (!$(this).next().is(":visible")) {
        $(this).next().slideDown();
      }
   })

   $(".main > li > ul > li > a").click(function() {
      $('.main ul ul').slideUp();
      if (!$(this).next().is(":visible")) {
        $(this).next().slideDown();
      }
   })

   $(".main ul ul li > a").click(function() {
      $('.main ul ul ul').slideUp();
      if (!$(this).next().is(":visible")) {
        $(this).next().slideDown();
      }
   })
  
});
ul.children {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main">
  <li class="page_has_children">
    <a href="#">Link</a>
    <ul class="children">
      <li class="page_has_children">
        <a href="#">Sub Link</a>
        <ul class="children">
          <li>
            <a href="#">Sub Sub Link</a>
            <ul class="children">
              <li><a href="#">Child Link</a>
              </li>
              <li><a href="#">Child Link</a>
              </li>
              <li><a href="#">Child Link</a>
              </li>
            </ul>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
        </ul>
      </li>
      <li class="page_has_children">
        <a href="#">Link</a>
        <ul class="children">
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
        </ul>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
  <li class="page_has_children">
    <a href="#">Link</a>
    <ul class="children">
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
  <li class="page_has_children">
    <a href="#">Link</a>
    <ul class="children">
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
  <li class="page_has_children">
    <a href="#">Link</a>
<ul class="children">

Answer №1

To enhance the efficiency of this code, consider implementing handles to minimize code duplication. One approach is to assign a class to parent links, allowing for easier addition of event handlers with fewer lines of code.

$(".parent-link").click(function() {
  var children = $(this).next(); //shortcut for the next ul
  var parents = $(this).parents(".children"); //select any uls above me

  //close all other uls not above me in the tree
  $('.children').not(parents).slideUp();
  
  //expand if closed
  children.filter(":hidden").slideDown();
})
ul.children {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main">
  <li class=".parent-link">
    <a class="parent-link" href="#">Link</a>
    <ul class="children">
      <li class="page_has_children">
        <a class="parent-link" href="#">Sub Link</a>
        <ul class="children">
          <li>
            <a class="parent-link" href="#">Sub Sub Link</a>
            <ul class="children">
              <li><a href="#">Child Link</a>
              </li>
              <li><a href="#">Child Link</a>
              </li>
              <li><a href="#">Child Link</a>
              </li>
            </ul>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
        </ul>
      </li>
      <li class="page_has_children">
        <a class="parent-link" href="#">Link</a>
        <ul class="children">
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
          <li><a href="#">Sub Link</a>
          </li>
        </ul>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
  <li class="page_has_children">
    <a class="parent-link" href="#">Link</a>
    <ul class="children">
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
  <li class="page_has_children">
    <a class="parent-link" href="#">Link</a>
    <ul class="children">
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
  <li class="page_has_children">
    <a class="parent-link" href="#">Link</a>
    <ul class="children">
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
      <li><a href="#">Sub Link</a>
      </li>
    </ul>
  </li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After fetching an HTML snippet using the $.get() method, Font Awesome icons are no longer visible

Experimenting with creating a seamless 'single-page' experience, I've managed to achieve this by implementing an event listener in jQuery for menu link clicks. This triggers the replacement of the existing content in my main div with an HTML ...

How can I create interactive markers on Google Maps?

I'm looking to incorporate Google Maps into a website. I will be receiving data on the client side in JSON format and I want to dynamically add markers based on that data. Additionally, I would like the markers to display iteratively, similar to the a ...

jQuery fails to make a POST request when the content type is set to application/json

I am utilizing jQuery version 1.10.1. My goal is to execute a POST request with the content type set to application/json. The code I have implemented is as follows: $.ajax({ type: "post", url: urlBase + "user/search", contentTy ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...

Obtain information from a database by leveraging the chosen Dropdown option through a combination of PHP and jQuery AJAX

I have updated my code below and I am receiving a "500 (Internal Server Error)" on my PHP code. Being new to PHP, jQuery, and Ajax, I have been struggling to find an example online that could help me solve my issue. Can someone kindly explain how I can di ...

Utilize AJAX to fetch and display the response from a Node JS route directly onto an HTML page

At the moment, I am retrieving client-side HTML/JS inputs (var1 and var2) which are then sent to server-side Node JS. The input values are stored in variables through an AJAX post call made to a specific route. What I want now is to define the values of v ...

React: Unable to set scrollTop on a Div under certain conditions

I've been grappling with this issue since this morning and I still can't pinpoint where I went wrong. My goal was to highlight text within a textarea input, even though I know it's not technically possible. However, I came across a clever wo ...

ASP Table extends into adjacent column

Having some trouble with the table layout here. In the screenshot, you'll notice a grid view within another gridview. There are currently 3 grid views - the main one and one in each table. I'm looking to move the description to the Price 2 column ...

Encircle a circle within the Progress Tracker

Is there a way to create a ring around the circle in this progress tracker, similar to the image shown here? The progress tracker is based on You can view an example here. The CSS approach used was: .progress-step.is-active .progress-marker { backgrou ...

What is causing my sprite image to be cropped?

I'm currently working on implementing a progress bar handle for my website. While the progress bar functions perfectly, I'm encountering an issue where the handle gets cut off when placed above the bar. Please refer to the attached image for refe ...

Looking for a method to select checkboxes using PHP? Consider utilizing a value to achieve this task

What is the correct way to define the isset function? When written as shown here, PHP does not register the click. `if(!isset($_POST['checkbox1']) || !isset($_POST['checkbox2']) || !isset($_POST['checkbox']) ) { ...

Aligning a group of divs within a right-floated div in a precise manner

I believe the concept can be explained best through an example: http://jsfiddle.net/kV9yn/16/ This is my simplified code. The issue arises when the rectangular divs on the right don't align properly. Ideally, I would like them to line up from left t ...

What is the best way to right-align navigation using bootstrap?

We are struggling to align our navigation items to the right side of our page. Despite using a container class and align-items-end, we have not been successful in achieving this. We must confess that this section is somewhat hastily put together, and we do ...

What is the easiest way to locate the ID of an iframe embedded within a webpage?

Currently, I am focused on developing small JavaScript/HTML5 ads for a webpage. Each advertisement comes with its own iframe that occupies a specific size and space on the page. In order to accommodate an expandable ad that needs to surpass the predetermin ...

Navigate to a designated tab by selecting a designated button in HTML

In my modal, there are two tabs called Login and Registration, along with buttons named Login_Button and Registration_Button. When I click on the Login_Button, I want to display the Login tab. Similarly, when I click on the Registration_Button, I want to ...

Tips for using jQuery to add or append a class to the final li element

I am currently struggling to understand why the last child of the li element is not being inserted into the last li. This module functions as a treeview, and my main objective is to add a class to the last li. Let me demonstrate with some sample code and ...

Troubleshooting: Magento checkout page keeps scrolling to the top

We are experiencing an issue where, during the one page checkout process, the next step is not automatically scrolling to the top of the page when it loads. After a user fills out all their billing information and clicks continue, the next step appears ha ...

Loading items into multiple containers using PHP AJAX pagination

I'm looking to implement a "load more" button on my website, but I'm facing a challenge due to my three-column layout. I want to load more items into their respective parent elements without disrupting the design. While I've used infinite aj ...

Trouble with toggling class "collapsed" in Bootstrap v3 Navbar-toggle when using multiple data-targets

When using the data-target attribute with multiple CSS selectors, the behavior of toggling the "collapsed" class in navbar-toggle does not work as expected. If only one selector is used, the class is toggled properly, but when multiple selectors are specif ...