Sub-menus at multiple levels are failing to automatically close child elements when clicked

Currently, I am tackling the challenge of creating a multi-level sub-menu that is triggered by clicks instead of hover actions. However, I'm facing an issue with closing child sub-menus when opening another one. It's crucial for all second-level sub-menus to be closed whenever a new sub-menu is opened.

You can view the project here: . Simply click on the "Productcategorieën" button to reveal the menu. Then, click on "Zonnepanelen" followed by "Verlichting". You'll notice that the "Zonnepanelen" sub-menu fails to close as expected.

Below is the snippet of code I'm currently using:

jQuery('.navigation li.menu-item-has-children > a').click(function (e) {
    e.preventDefault();
    if (!jQuery(this).parent().hasClass('open-submenu')) {
        jQuery(this).parent().parent().find('.open-submenu').removeClass('open-submenu');
        jQuery(this).parent().addClass('open-submenu');
    } else {
        jQuery('.navigation li').removeClass('open-submenu');
        jQuery(this).parent().removeClass('open-submenu').find('.open-submenu').removeClass('open-submenu');
    }
});

Any suggestions on how to resolve this issue would be greatly appreciated!

Answer â„–1

There's a simple reason behind this issue - failure to close the already opened sub-menu.

Look at this instruction :

jQuery(this).parent().parent().find('.open-submenu').removeClass('open-submenu');

The parent().parent() part only goes up to the .menu-item level of that specific .sub-menu, leaving other .open-submenus untouched in different .menu-items.

To solve this, ensure you close any existing .open-submenu before opening a new one.

Try out the following revised code :

jQuery('.navigation li.menu-item-has-children > a').click(function (e) {
    e.preventDefault();
    if (!jQuery(this).parent().hasClass('open-submenu')) {
        jQuery('.navigation').find('.open-submenu').removeClass('open-submenu');
        jQuery(this).parent().addClass('open-submenu');
    } else {
        jQuery(this).parent().removeClass('open-submenu').find('.open-submenu').removeClass('open-submenu');
    }
});

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

How come the CSS for my angular ngx-mat-datetime-picker and mat-datepicker collide when they are both present on the same page?

Within the same form, I have two input fields stacked under each other. One is an ngx-mat-datetime-picker and the other is a mat-datepicker. Individually, they function correctly. However, when I open them for the second time, the one I opened first appear ...

Update the label to an input field

My task involves adjusting the label that is generated in an input form using CakePHP and JQuery. $info = "test"; echo $this->Form->input('tipo_de_venta', array('type' => 'select', 'label' => 'Tipo ...

Utilize Python win32 to incorporate a signature into Outlook emails

I'm currently working on a code to automate email sending. The code is functioning properly, but I'm facing an issue with adding my email signature to the message body. Initially, I assumed that using mail.Display() would automatically include t ...

Error VM5601:2 encountered - Unexpected token "<" found in JSON at position 10

I am trying to retrieve data using Ajax and jQuery, but I keep encountering an error that I cannot figure out how to fix. VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 Below is the code I am working with. Model public f ...

Prevent duplicate rectangles by cleaning up dirty rectangles

I'm looking to optimize the performance of my game by only clearing the necessary parts of the canvas that contain animations. Below is a snippet of my code: this.draw = function(context) { context.clearRect(this.oldx, this.oldy, this.width, ...

My current scroll animations are problematic as they are causing horizontal scrolling beyond the edge of the screen

I've implemented scroll animations on various elements of a website I'm constructing. The CSS rules I'm utilizing are as follows: .hiddenLeft { opacity: 0; filter: blur(5px); transform: translateX(-090%); transition: all 1s; ...

Nuxt.js implemented with Auth using jwt refresh tokens

I've implemented the Auth library in my Vue/Nuxt project and have successfully set up JWT Authentication. However, I'm encountering an issue with the refresh token. The refreshToken cookie is consistently being set to null: https://i.sstatic.ne ...

Using Django and Jquery to pass multiple values to HTML, with one value stored in a .js file

Here is an example of HTML code: {% for m in mortgages %} <input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{ m.MonthlyPaid }}'> {% endfor %} If used for a selection menu: {% for ...

The necessity of using Adobe Photoshop for optimizing a Web Template

My interest lies in utilizing web templates, such as the one referenced here:- templete However, within its details tab, it specifies that the following software is required:- Adobe Photoshop CS+ Sublime Text2 or later, Notepad++, Dreamweaver CS5.5+(Co ...

Adjust the transparency of a navigation bar independently from the transparency of the text within the navigation bar

Seeking assistance on adjusting the opacity of this navbar without affecting the text within it. Any tips on changing the text color as well? <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#" ...

The class name feature on the Drawer component is malfunctioning

React and material-ui are my tools of choice, but I've hit a roadblock. I'm attempting to define some custom CSS behavior for the drawer component, using the className property as recommended. However, despite following the instructions, it' ...

Spacing that separates elements vertically within a listing

I'm facing an issue with a list of elements arranged in a row that wraps onto a second line due to space constraints within the container. Is there a way for me to introduce additional spacing between the first and second line of these elements, bear ...

Issues with the aligning of buttons using the justify-content property

The issue I'm facing involves a parent container with 3 buttons nested inside. The parent container is set to display:inline-flex, however, the justify-content: space-between property is not behaving as expected. Each button has a defined max-width in ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...

Optimal Procedure for New Users Form (Jade / Angular) in HTML

I'm currently working on integrating a form into my app for users to create tasks. This form should only appear the first time a user attempts to create a task. As someone who is not very experienced with frontend development, I find myself wondering ...

Items in the Vue.Draggable display can be arranged on both the left and right

Recently delving into Vue.js, I am utilizing Vuedraggable for item dragging in my project. Currently, the items in the draggable div are shown as Text 1 Text 2 Text 3 Text 4 Is there a way to rearrange them to display like this? Text 1 Text 2 Text 3 T ...

Initiate a new animation as soon as the others have completed

When a user clicks, I want to animate multiple elements: $('.serie').click(function(){ $("#fade1").fadeIn(2000); $("#fade2").fadeIn(2000); $("#fade3").fadeIn(3000); $('afterall').addClass("newclass",700); }); However, I ne ...

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

Display Loading Spinner with Bootstrap on Form Submission

This Django project features a Bootstrap spinner within a button, as seen in the code snippet below: <form method="POST" id="pdfUploadForm" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <b ...