Javascript menu toggle malfunctioning with sub-menus

I am in the process of creating a responsive menu for a complex website. The horizontal menu transitions into a vertical layout on smaller screens, with javascript used to toggle the sub-menu items open and closed when clicked. One issue I am facing is with the product section, which has another level of sub-menu that does not behave as expected – only the third level items close when clicked, not the parent item.

Below is the code snippet:

<nav id="navigation">
<ul id="nav-list"> 
    <li class="nav-list_item nav-about"><a href="....">About us</a>
        <div id="about-drop" class="dropdown">
            <ul>
                <li>....</li>
                <li>....</li>
            </ul>
        </div>
    </li>
    <li class="nav-list_item nav-products"><a href="....">Products</a>
        <div id="prod-drop" class="dropdown">
            <div id="subnav_products1" class='targetDiv'>
                <div class="drop-section">
                    <h5 class="nav-title">Purpose</h5>
                    <ul>
                        <li>...</li>
                        <li>...</li>
                    </ul>
                </div>
                <div class="drop-section">
                    <h5 class="nav-title">Series</h5>
                    ul>
                    <li>...</li>
                    <li>...</li>
                    </ul>
            </div>
        </div>
        </div>
    </li>
</ul>

Here is the corresponding javascript:

if ($(window).width() <= 760) {
$('li.nav-list_item').click(function(){
    $('li.nav-list_item').not(this).find('ul').hide();
    $(this).find('ul').toggle();
});
}

I suspect the issue arises from the fact that when the parent item (products) is clicked, the ul elements close as per the script, but the nested nav-title items (Purpose/Series) remain open and cannot be closed. I have been attempting to address this problem without success. Any suggestions on how to ensure that clicking on the title items closes the third-level menu while clicking on the parent item (Products) closes the title items?

Answer â„–1

Unfortunately, I am unable to troubleshoot your code since the example you provided is not functional. I recommend visiting Codepen to create a working demo where we can identify and address the issues.

Additionally, it is feasible to incorporate navigation using only CSS by utilizing hidden radio buttons or active states.

Answer â„–2

$('li.nav-list_item a, .nav-title').on('click', function(e){
    e.preventDefault();
    
    var el = $(this);
    el.parent().siblings().find('> .dropdown:visible, > ul:visible').toggle();
    el.parent().find('> .dropdown, > ul').toggle();
});
#nav-list .nav-list_item {
  display: block;
}
#nav-list .nav-list_item .dropdown{
  display: none;
}
#nav-list .nav-list_item .dropdown .drop-section ul {
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav id="navigation">
<ul id="nav-list"> 
    <li class="nav-list_item nav-about"><a href="#">About us</a>
        <div id="about-drop" class="dropdown">
            <ul>
                <li>....</li>
                <li>....</li>
            </ul>
        </div>
    </li>
    <li class="nav-list_item nav-products"><a href="#">Products</a>
        <div id="prod-drop" class="dropdown">
            <div id="subnav_products1" class='targetDiv'>
                <div class="drop-section">
                    <h5 class="nav-title">Purpose</h5>
                    <ul>
                        <li>...</li>
                        <li>...</li>
                    </ul>
                </div>
                <div class="drop-section">
                    <h5 class="nav-title">Series</h5>
                    <ul>
                      <li>...</li>
                      <li>...</li>
                    </ul>
            </div>
        </div>
        </div>
    </li>
</ul></nav>

I have included the necessary code for navigation with dropdown menus. Feel free to make any modifications as needed for your project. If you need further assistance, please provide a Fiddle link for easier collaboration.

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

Exploring a different method for implementing animations during UI-router state transitions

My product owner presented me with a seemingly impossible challenge to create animations between states. I utilized ngAnimate and thought I had a brilliant solution - only to be told it wasn't what they wanted. "This isn't what I had in mind," h ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

utilizing jquery ajax for image uploading with php and mysqli

When trying to upload an image URL using AJAX into the database, I encountered an error upon submitting the form. My goal is to upload the image URL into the database without refreshing the page. The specific error message I received was: GET 400 (Bad Re ...

What is the best way to set the width of an inner element as a percentage of the Body's width?

Applying a percentage width to any inner element of a page will typically result in that element taking a percentage of its parent container's width. Is there a way to specify the width of an inner element as a percentage of the overall Body width, r ...

Using inline JavaScript to style an element when clicked

Looking for assistance with styling a link. I've connected an external stylesheet to my HTML file, so that part is all set. The goal is to modify the text-decoration when the onclick event occurs. Here's what I currently have: <a class="dopel ...

Leveraging configuration files for HTML pages without any server-side code

I am currently working on developing an app using phonegap. At the moment, I have the reference to a script in every page like this: <script language="javascript" src="http://someServer/js/myscript.js"></script> If the server 'someServer ...

Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this: <div *ngFor="let item of items | async"> <div class="row"> <div class="col-lg-6"> <div class="card ...

Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method: function MyController($scope) { $scope.clock = new Date(); var updateClock = function() { $scope.clock = new Date(); }; setInterval(updateClock, 1000); }; The HTML asso ...

Implement a CSS style for all upcoming elements

I'm currently developing a Chrome extension tailored for my personal needs. I am looking to implement a CSS rule that will be applied to all elements within a certain class, even if they are dynamically generated after the execution of my extension&ap ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

Is it recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...

Altering the href text within a script causes the text to disappear instead of updating

Function Triggered by Button Click: function LoadEnglishText() { document.getElementById("txt_whatwedo_learnmore2").innerHTML = "here."; } HTML Link to be Updated: <a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier ...

Refreshing CSS-Element-Queries following an ajax request

I’ve been utilizing css-element-queries from the https://github.com/marcj/css-element-queries repository to tailor styles based on an element's dimensions. However, I encountered an issue when dynamically adding elements via ajax calls. The new elem ...

Is it possible to implement MV* in Polymer using models and services as polymer elements?

Imagine I want two views (polymer-elements) to share a model, how can this be achieved? In Angular, the model would reside in a singleton service that is injected into the views, allowing both views to access the same data source. I attempted to replicat ...

Dealing with uncaught promise rejection while using the 'opn' npm package in Docker

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Exited with code 3 I encountered this error while trying to open links using a module within a Docker container. The code functioned fine on my local machine without D ...

The issue you're encountering in React Native Expo is a restriction where Hooks can only be invoked within the body of a function

I'm currently working on a mobile app with React Native expo, but I've encountered an issue: Invalid hook call. Hooks can only be called inside the body of a function component.... I have checked other solutions on Stack Overflow and verified th ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

Creating a conditional npm script that depends on the output of another: a step-by-step guide

I've encountered this problem before while setting up npm scripts, and I haven't been able to find a solution yet. I'm hoping to make the solution compatible with both Mac and Windows environments. I'm working on splitting up the logic ...

Unable to set two image layers on HTML canvas to display in different colors as anticipated

I am facing a challenge with stacking 3 images: an outline, a white base, and a pattern that is also white. My goal is to layer these images where the base is at the bottom with one color assigned to it, the pattern is stacked on top with a different color ...

Incompatibility problem with IE

Encountered an issue in Internet Explorer: Error message: Object doesn't support property or method 'block'. The jQuery code I'm using is : showProcessingMessageAndBlockForm: function () { $("#checkoutContentPanel").block({ me ...