Toggling the visibility of <ul> and <li> elements with Javascript upon clicking

I have organized a few categories and their sub-categories on my website using nested <ul> <li> tags. When a user clicks on a category, I want all the related sub-categories to become visible. Initially, none of the sub-categories are visible.


This is how it is structured in the body:

<ul>
   <li class="dropdown">Data mining and data warehousing
      <ul>
           <li>Data mining techniques</li>
           <li>Knowledge discovery</li>
      </ul>
   </li>

    <li class="dropdown">Soft computing and artificial intelligence
       <ul>
            <li>Fuzzy systems</li>
            <li>Neural networks</li>
       </ul>
    </li>
</ul>

This is the CSS styling used:

li.dropdown ul {
display : none;
}

I've included the following JavaScript script in the HTML head section:

<script type="text/javascript">
$('li.dropdown').click(function() {
   $(this).children('ul').toggle();
});
</script>

The initial effect works as intended with all sub-categories hidden. However, I would like for when a category is clicked, such as Data mining and data warehousing, then its sub-categories (Data mining techniques and Knowledge discovery) should also become visible.


Additionally, when another category is clicked, the previously opened categories' sub-categories should collapse again. How can I achieve this?

Answer №1

In this approach, the main goal is to conceal all elements except for the selected li, and then switch on/off subcategory visibility for that specific item:

$('li.dropdown').click(function() {
   $('li.dropdown').not(this).find('ul').hide();
   $(this).find('ul').toggle();
});

If you'd like to see an example, feel free to check out this jsFiddle.

Answer №2

Give this a go:

$('li.dropdown').click(function() {
   $(this).find('ul').toggle();
});

Answer №3

$('li.dropdown').on('click', function() {
   $('.dropdown ul').hide();
    $(this).children('ul').show();
});

Give it a shot here http://jsfiddle.net/7NYhe/

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

What is the most efficient method for converting an array-like object into an actual array?

Imagine a scenario where we have the following: var obj = {"1": 1, "2": 2, "5": 5}; Now, suppose I wish to transform it into an array that looks like this: var obj = []; obj[1] = 1; obj[2] = 2; obj[5] = 5; Is there a way to achieve this transformation? ...

Master the art of creating click events using only CSS

Is it possible to achieve this example using only CSS? If not, what would be the alternative solution? Any JSFiddle examples would be greatly appreciated! How can I also add slashes - should I use an image or can it be done with CSS? And what about the t ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

Issues with the functionality of the Handlebars template are causing it to

Currently experimenting with Handlebars templates within my express/node.js application. I have created a template and corresponding .js files, but unfortunately, they are not functioning as expected. While the page correctly displays the unordered list&ap ...

The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue? Below is my updated code: // Define the canvas / graph dimensions var margin = {top: ...

Error: Unable to access the 'classList' property of null in HTMLSpanElement.expand function

Encountering a minor issue with my javascript code. Following a tutorial for a seemingly simple task: link What I did: Adapted the HTML from the tutorial to fit my desired visual outcome while maintaining correct class and id attributes. Utilized identic ...

Using jQuery to swap out intricate background designs

I'm attempting to use jQuery to change the background-color of an element from: background: transparent linear-gradient(#C0B 45%, #C0B) to: background-color:#000; Unfortunately, my attempt to remove the background property with .removeAttr() has n ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

Creating a custom HTML5 canvas with images from a JSON array

I am currently working on a project to develop a unique slideshow feature by hosting images in an external JSON array and then loading them onto an HTML page. The next step is to insert these images onto an HTML5 canvas. While I have successfully loaded a ...

Cypress - Adjusting preset does not impact viewportHeight or Width measurements

Today is my first day using cypress and I encountered a scenario where I need to test the display of a simple element on mobile, tablet, or desktop. I tried changing the viewport with a method that seems to work, but unfortunately, the config doesn't ...

Unable to retrieve valid inputs from text fields by utilizing jQuery selectors

Extracting information from text fields is my goal. Specifically, these fields contain dates which consist of three parts: the year, month, and day. The dates are divided into two sections - the first date and the last date, serving as boundaries for a sea ...

High-resolution visuals and interactive scripting

I am currently using pannellum (http://www.mpetroff.net/archives/2012/08/28/pannellum-1-2/) with Three.js to work on local files. Everything works smoothly for small files, but when I try to load a 5000 x 10000 image, it fails to load. I'm wondering w ...

Find items where a certain value matches any of the values in another array and return them

I'm seeking assistance with a specific task. I have an object structured as shown below: SOMEKEY: { "key1": val1, "key2": val2 } Additionally, I have an array that contains string values like this: [stringA, stringB, stringC ...

Event bubbling does not occur in elements outside of the DOM

I am facing an issue with a DOM element that has not been added to the DOM yet, but I want to trigger a DOM event on it. The event is not supposed to bubble up, however, when using jQuery, it does. This behavior seems odd to me. This strange phenomenon c ...

The functionality of the Jquery script ceases to work after I make alterations and then refresh the original elements for selection

Encountering challenges with jquery's .html() function. The following code modifies a text box input value from "Enter email address" to "" when focused, and reverts it back to "Enter email address" if left empty on blur. I am utilizing jquery's ...

Can a line be created using only CSS without the need for an additional HTML element?

There have been many inquiries regarding drawing lines without adding an additional HTML element. Consider this scenario with an HTML div element: <div class="myDiv"></div> Accompanied by the following CSS: .myDiv{ width: 100px; height: ...

Is it possible that MapBoxGL installation with Expo doesn't function properly for web?

I have been working on building an app featuring a map using the MapBoxGL library in Expo. I followed the installation instructions provided by the library, which can be found here. After completing the installation, I proceeded to write the code below to ...

Exploring the functionality of scrollTo in React

I'm currently working on developing a carousel feature that should scroll when the user interacts with the navigation buttons. However, despite my efforts, I am facing an issue where the scrolling functionality is not working as expected in my code sn ...

Is it possible to retrieve and display an object from an API using its unique ID?

I created a straightforward application. The main page displays a list of movies fetched using an API, and upon clicking on a particular movie, it leads to a new page with detailed information about that movie. On the details page, another API call is ma ...