Guidelines on Implementing a Three-Level Jquery Accordion Menu

Here is a snippet of jQuery code that I am working with:

$(document).ready(function(){
$("#accordion2 h3").click(function(){
    //slide up all the link lists
    $("#accordion2 ul ul").slideUp();
    //slide down the link list below the h3 clicked - only if its closed
    if(!$(this).next().is(":visible"))
    {
        $(this).next().slideDown();
    }
})
})

Below is the corresponding HTML structure:

<div id="accordion2">
<ul>
    <li>
        <h3>Articles</h3>
        <ul>
            <li><a href="#">Nature</a>
            <ul>
              <li>Wild life</li>
              <li>Flowers</li>
              <li>Animals</li>
            </ul>
            </li>
            <li><a href="#">Earth</a></li>
            <li><a href="#">Space</a></li>
            <li><a href="#">Ocean</a></li>
            <li><a href="#">Land</a></li>
        </ul>
    </li>
</ul>
</div>

I am looking to modify the jQuery code so that the user can slide down the "Nature" section and view its contents, which includes a third level menu.

Answer №1

Does this meet your requirements? If not, please provide further clarification.

$(document).ready(function(){
    $("#accordionSection h2").click(function(){
        $(this).next().slideToggle();
    })
     $("#accordionSection ul ul li a").click(function(){
        $(this).next().slideToggle();
    })
})

View live demonstration here

Answer №2

Accordion Menu Example: JSFiddle

HTML Structure

<ul id="menu" class="menu">
<li><a href="#">Item A</a>
    <ul class="sub-menu">
        <li><a href="#">Sub Item A</a>
            <ul class="sub-menu">
                <li><a href="#">Sub sub item A</a>
                    <ul class="sub-menu">
                        <li>Sub Sub Item A</li>
                        <li>Sub Sub Item B</li>
                    </ul>
                </li>
                <li>Sub sub item B</li>
                <li>Sub sub item C</li>
            </ul>
        </li>
        <li>Sub Item B</li>
        <li>Sub Item C</li>
    </ul>
</li>

<li><a href="#">Item B</a>
    <ul class="sub-menu">
        <li>Sub Item D</li>
        <li>Sub Item E</li>
        <li>Sub Item F</li>
    </ul>
</li>
</ul>

JavaScript Function

function initializeMenu() {
    $(".sub-menu").hide();
    $(".current_page_item .sub-menu").show();
    
    $('#menu li a').click(function() {
        var checkElement = $(this).next();
        
        if (checkElement.is('ul') && checkElement.is(':visible')) {
            return false;
        }
        
        if (checkElement.is('ul') && !checkElement.is(':visible')) {
            console.log(checkElement.parentsUntil('#menu'));
            $('#menu ul:visible').not(checkElement.parentsUntil('#menu')).slideUp('normal');
            checkElement.slideDown('normal');
            return false;
        }
    });
}

$(function() {
    initializeMenu();
});

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

Is it still beneficial to incorporate image sprites in the design of a mobile web app?

As I work on developing a mobile web app, I find myself debating whether to use individual images or stick with image sprites similar to what I do for my desktop site. My main concern is the potential increase in file size from consolidating all the images ...

Set the value of one email input to another email input in AngularJS

I'm having trouble trying to link an email input field to another in angularjs without success. Here is what I have attempted so far: <div class="row-fluid"> <div class="control-group span12"> <label for="email">Email</labe ...

What is the reason for my Firestore listener consistently retrieving data from the server despite having offline persistence enabled?

Incorporating Firebase JavaScript Modular Web Version 9 SDK into my Vue 3 / TypeScript application. My understanding is that when utilizing real-time listeners with offline persistence in Firestore, the process should proceed as follows: Upon initializat ...

Choose a JavaScript function by clicking on the HTML text

As a beginner in the world of coding, I have been diving into JavaScript, HTML, and CSS. Inspired by fictional supercomputers like the Batcomputer and Jarvis, I've challenged myself to create my own personal assistant to manage tasks, games, programs, ...

NextJS was throwing a warning at me, while Firebase hosting was giving me an error regarding the absence of unique keys for children in lists, even though I

I've been troubleshooting this warning for quite some time, but I can't seem to resolve it. The warning reads as follows: Warning: Each child in a list should have a unique "key" prop. Check the top-level render call using <ul>. ...

Easy Steps to Align a Rotated Table Header

I am looking to rotate the header table using CSS while keeping all text together. Here is my CSS code: th.rotate { height: 100px; white-space: nowrap; } th.rotate>div { transform: rotate(-90deg); } Here is how I have applied this CSS: ...

Can a variable be declared within the path references of the Firebase database?

In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Fire ...

Processing Wordpress forms using Ajax and PHP

Currently, there is a form on my website that sends data to a PHP file. When the form is submitted, users are taken to a blank PHP file. I would like the form to either submit via AJAX or redirect after processing the mail function. Thank you for any help! ...

Stop flex items from expanding larger than their sibling elements

Is there a way to prevent a flex item from growing bigger than its siblings? Check out the example on CodeSandbox: LINK Here is the sample code: <div class='wrapper'> <div class='box one'></div> <div class ...

There seems to be an issue with the functionality of chrome.storage.local.set()

Struggling with Chrome storage handling, I have reviewed the newest documentation for Chrome storage and implemented the following code snippet (found within an AJAX call success function, where info.userName is a value fetched from my backend program): ch ...

How can I locate the quantity of items within an embedded document in MongoDB?

Examining my schema, it appears like this: name: value: p_vars: { name1: {}, name2: {}, } My goal is to determine the number of items in p_vars. Assuming the interpreter is JavaScript, I attempted the following: db.collection.findOne().p_vars.l ...

Updating the state on a click event triggered by a MenuItem in React using Material UI

I'm currently working on implementing state changes based on dropdown selections using Material UI. However, I've encountered an issue where the code snippet below (simplified) only returns the list item, and I'm unsure what steps to take n ...

The use of CSS float creates spaces between elements

Is there a way to stack the green DIVs on top of each other without any space between them in the given simple HTML code? I'm puzzled by the gap between the third and fourth green DIVs. * { margin: 0; } .left { width: 20%; background-color: # ...

Could you provide me with some information regarding the relationship between screen resolution and screen size?

When checking my website on different screen resolutions, I rely on a tool called Screenfly from quirktools.com. While using this tool, I came across an interesting feature - the display icon in the top left corner with a dropdown menu showing resolution ...

The data type 'void' cannot be assigned to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'

Can you assist me in understanding what has occurred and provide guidance on the necessary steps to resolve it? I am currently working on a website where I am in need of hooks to update the state. The issue seems to be related to the onClick events within ...

Tips for applying unique CSS classes to individual templates in Joomla

I manage a website at www.kadamjay.kg using an RT template system where each language version has its own unique template. However, when I add a class to a specific element, it only changes on one template and there are no additional templates in the pat ...

Turn off slider trace animation?

Check out the slider component in MUI here: https://mui.com/material-ui/react-slider/ I'm currently exploring how to disable the animation on the nub so it moves instantly to the new position. Any advice on how to achieve this? ...

Glass-pane or angular/HTML overlay on a designated element

Is there a way to create a glass-pane effect, like an hourglass symbol on a semi-transparent layer, within the boundaries of an HTML element E? The goal is to have the glass-pane only overlap the area within E's boundaries. When the glass-pane is ac ...

JavaScript: Increasing the date by a certain number of days

I've been researching various topics and so far, I haven't come across one that addresses my specific issue. Here's the task at hand: 1) Extract a bill date in the mm/dd/yy format, which is often not today's date. 2) Add a dynamic ...

Navigating between pages using React-router-dom

Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...