Toggle the menu using jQuery on unordered list items

Below is the HTML code I am using :

<ul class="main-block">

 <li class="firstLevel">
   <a href="#category">EXAMPLE CATEGORY 1</a>
     <ul class="dijete">
       <li class="child">
          <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 11.</a>
       </li>
       <li class="child">
          <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 1.1</a>
       </li>
     </ul>
 </li>

 <li class="firstLevel">
   <a href="#category">EXAMPLE CATEGORY 2</a>
     <ul class="dijete">
       <li class="child">
          <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 2.1</a>
       </li>
       <li class="child">
          <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 2.2</a>
       </li>
     </ul>
 </li>

</ul>

Here's my jQuery code for toggle():

<script type="text/javascript">
    var $j = jQuery.noConflict();
    $j(function() {
        $j('li.firstLevel').click(function(){
            if($j('ul.dijete').hasClass('active')){
                $j(this).find('ul.dijete').removeClass('active');
            }else{
                $j(this).find('ul.dijete').addClass('active');
            }
        });
    });
</script>

However, I am facing an issue where when I have one category (EXAMPLE 1) active and then click on another category (EXAMPLE 2), the first one remains open and the second one does not open up.

Why is the hide-show functionality not working as expected?

How can I show the second sub-menu and hide the first one when clicking on a different category? This behavior is not working in either way.

Answer №1

Implement the following syntax:

let $ = jQuery.noConflict();
$(function() {
    $('li.firstLevel').on('click', function(){
        $(this).children('ul.child').toggleClass('active');
    });
});

Answer №2

Check out this functional example

If you want to toggle the 'active' class, you can use the toggleClass() function. Before adding the 'active' class to the clicked item, make sure to remove it from other items with the class 'child' like this:

$('ul.child').removeClass('active');

I hope this solution proves useful.


See the working code below

$('li.firstLevel').click(function(e){
  e.preventDefault();

  $('ul.child').removeClass('active');
  $(this).find('ul.child').toggleClass('active');
});
.active{
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main-block">

  <li class="firstLevel">
    <a href="#category">EXAMPLE CATEGORY 1</a>
    <ul class="child">
      <li class="child">
        <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 11.</a>
      </li>
      <li class="child">
        <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 1.1</a>
      </li>
    </ul>
  </li>

  <li class="firstLevel">
    <a href="#category">EXAMPLE CATEGORY 2</a>
    <ul class="child">
      <li class="child">
        <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 2.1</a>
      </li>
      <li class="child">
        <a href="some-sub-category.html">EXAMPLE SUB-CATEGORY 2.2</a>
      </li>
    </ul>
  </li>

</ul>

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

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

Add a luminous shine to a THREE.TextGeometry element within the Three.js environment

After conducting extensive research on Google, I am still trying to determine if it is possible to achieve a glow effect within the three.js environment. My goal is to create a glowing effect based on TextGeometry rather than a simple primitive shape like ...

Is it possible to create a single code that can be used for various buttons that perform the same function?

Whenever I click the right button, the left button appears and when I reach the last page, the right button disappears. However, this behavior is affecting both sections. Is there a way to write separate code for each section? I managed to make it work by ...

Having trouble loading the .php file with my Ajax request

Attempting to retrieve data from the postcode.php file and display it in a #postcodeList div, but encountering issues as nothing happens. Upon inspecting the postcode.php file, it seems to be outputting all the correct information. var loadicecream = do ...

Steps for preventing form submission when the username is unavailable

After checking the availability of the user name, I encountered an issue where the form still gets submitted even if the username is not available. Updated Code: <SCRIPT type="text/javascript"> $(document).ready(function(){ $("#emailch").change(fu ...

Retrieve the final ID of a dynamic div

Unable to find a solution, I am attempting to retrieve the ID of the most recently created div on the page. The code I have been using with .last() doesn't seem to be functioning correctly. My syntax may be incorrect, as I can't seem to extract a ...

When executing multiple promises in parallel, the function Promise.all() does not support the spread() method

I'm attempting to simultaneously run two promises using sequelize, and then display the results in a .ejs template. However, I keep encountering the following error: Promise.all(...).spread is not a function Below is my code snippet: var environme ...

Enhancing Octahedron Geometry in Three.js: Incorporating Materials Array

Is it possible to apply different materials to each face of a THREE.OctahedronGeometry? I have successfully done this with box objects, but when I try with THREE.OctahedronGeometry, I only see the first material on all faces. How can I achieve this with ...

Aligning text inputs inline within a Bootstrap form for a cleaner and organized

I am currently working on designing a form using Bootstrap, and I have a specific requirement where the first name and last name fields need to be displayed inline while the rest of the form remains unchanged. Although I have managed to make the inline fu ...

The JSON retrocycle function selectively converts certain references only

I have an array of objects with some cyclic references. To handle this, I used JSON.decycle when sending the object via JSON and JSON.retrocycle on the receiving end. For example: var refactor_data = JSON.retrocycle(JSON.parse(event.data)); The issue is ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...

(Javascript - Arrays) Find the leftmost and rightmost connected characters

Looking for the leftmost and topmost connected '1' character in a 2D matrix? Find the most left & top connected '1' character Find the most right & bottom connected '1' character EDIT 2.0: To start, provide the coordina ...

Tips on personalizing buttons within Telerik form or Kendo form

Having recently started working with Telerik UI, I am struggling to customize a Kendo form in ASP.NET Razor Pages. Specifically, I am trying to rename a button but cannot locate the button field within the code. Despite following the guidelines provided in ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

Any recommendations for updating input in a directive without relying on $broadcast?

I am currently facing an issue with my contact list on controller A. Whenever I select a contact, the contact's information gets broadcasted to controller B and also to the datepicker directive in controller B. Although this method works, I am wonderi ...

Issue with Typescript in react: JSX element lacks construct or call signatures

After upgrading TypeScript, I encountered the error mentioned above in one of my components. In that component's render method, I have the following code: render() { const Tag = props.link ? 'a' : 'div'; return ( < ...

What is the best method to set variables to zero using this array in JavaScript?

I am looking to extract strings from an array and set them all to zero. The original array consists of: var myArray = ["apple", "banana", "cherry", "date"]; The expected outcome should be: var apple = 0; var banana = 0; var cherry = 0; var date = 0; I ...

What is the process for sending a cross-site request to Azure's mobile service API?

When working with Azure's MobileServiceClient, jquery, or AngularJS, I have encountered a dilemma. The service necessitates a custom header, and now I am uncertain if it is possible to incorporate both simultaneously. ...