Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this:

.navbar ul li ul 

I would like the child menus to be hidden and only shown when the parent menu is clicked.

Although I attempted to achieve this with the following code, it was unsuccessful.

$(".navbar ul li").each(function(index, element) {
    if ($(this).children('ul').attr('class')){
    }
    else {
        $(this).find('span').remove();
    }
});

$(".navbar ul li span").click(function(){
    $(this).toggleClass('ss');
    $(this).parent('li').toggleClass('active-mobile');
    $(this).parent('li').children('ul').slideToggle();
});

Answer №1

Your current code seems to be quite complex. Maybe consider simplifying your approach.

To start, hide all submenus using CSS:

#nav li > ul {
    display:none;
}

Then, you can toggle a class to show the selected element (with optional animation):

$('ul#nav > li').click(function () {

    $(".show").removeClass("show").find("ul").slideUp();
    $(this).addClass("show").find("ul").slideDown();    
});

This is a basic dropdown menu that you can build upon by adding more features. For example, in the provided demo, there's a check to see if the clicked element is already visible and toggles it accordingly. However, this basic code should give you a good starting point.

Check out the Demo

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

Encountered an issue with setting the property of "something" to undefined when attempting to generate an array sorted by dates

After seeking help from @Kato on Stack Overflow regarding sorting a Firebase AngularFire array into weeks and days, I encountered an error where I cannot set a property of "something" that is undefined. To provide more context, I created a detailed Plunke ...

Can I use jQuery to fetch a PHP variable?

Is there a way to extract a PHP variable from jQuery? Let's say I am using the jQuery POST function like this: $.post("login.php", {username:username, password:password}, function(data){ $('section').html(data); }); Rather than displa ...

The CSS style is missing from the print preview

I've designed a style specifically for printing like this: #content .inner h2 { background: Red; border-bottom: solid 1px #dfdfdf; color: #000000; font-size: 20px; padding-left: 10px; } However, the red color doesn't show up in the print previe ...

Troubleshooting issues with JSON compatibility within the OnChange event

Initially, I wrote this code to retrieve a single data point. However, I realized that I needed more fields returned when the drop-down select menu triggered an onchange event. So, I switched to using JSON, but now it's not returning any data. The dro ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Fetching information via AJAX to populate a whitelist for Tagify

Attempting to retrieve data via ajax for tagify whitelist, but encountering the following error: ReferenceError: Can't find variable: clist Here is the code snippet: $.ajax({ url: '/ajaxget/tags', method: &ap ...

What are the steps to make ng-show functional in an AngularJS application?

I am attempting to implement a hover effect where an image is displayed over another image upon hovering over its container. I have been trying to achieve this using Angular and ng-show, but for some reason, the image with the ng-show attribute remains hid ...

Hide popup using HTML when clicking outside of it

Currently, I have implemented Bootstrap Popover with HTML content using the code snippet below. This code is based on the answer provided at . $(".song-status-link").popover({ html: true, placement: 'bottom', ...

The MDBDataTable features header sections at both the top and bottom, but the filters UI seems to be

Currently, I am working with MDBDataTable and encountering an issue with the double heading that appears both on top and bottom of the table. I am unsure how to remove it. The code snippet in question is as follows: There is a function that retrieves and ...

Utilizing a jQuery click event to modify the placement of a table

I have a request regarding the tables within the #middlebox. I would like to be able to rearrange the table positions by clicking on the list items. For instance, if the current order of the tables is starter -> soup -> seafood, clicking on the #seaf ...

Tips on sending a JSONP token with an AJAX request

I have been researching JSONP online, and I came across information stating that JSONP requires a token. To adhere to this requirement, I added "product" in front of my JSON code. However, I am unsure if this is the correct format for JSONP. Please let me ...

A step-by-step guide to activating multi-selection in the Primary SideBar of Visual Studio Code using your custom extension

Currently, I'm in the process of developing an extension for Visual Studio Code where I've added a new activityBar containing treeViews that showcase information pulled from a JSON file. My goal is to enable users to multi-select certain displaye ...

Creating multiple blocks with a 100% height in HTML

Is it true that a parent element must have a fixed height to use percentage-based height? For example, 500px. I'm designing a grid with divs arranged hierarchically. The parent has a fixed height of 500px, and the children have percentage heights, ea ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

jquery: conditions fail to execute

Looking at the code snippet provided, it appears quite straightforward. The intention is to display an alert labeled "Trigger 2" if the variable "ret" returns a value of "fail". However, there seems to be a glitch with the IF statement causing it to trigge ...

Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is: KM driven per year * Avg KM/100L / Price of fuel I have managed to display each slider's individual values, but I am uncertain about how to show t ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

How come e.target.value always shows the most recent value?

Starting out in HTML and I have a question regarding input. Here is the HTML code I am working with: <input type="text" value="abc" onChange={(e) => { console.log(e.target.value); }}/> I am puzzled because even though the default v ...

two adjacent DIV elements with matching heights

Currently, I am in the process of developing an internal web page with a wrapper DIV structure based on recommendations from an online tutorial. Within this wrapper, there are different sections including a header, mainnav, content, sidenav, and footer. Th ...

Mat-SideNav in Angular Material is not toggled by default

<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>{{applicationN ...