creating a basic dropdown menu with jQuery toggleClass

I am facing an issue with the code below. Whenever I hover over a menu, all submenus in the dropdown open. How can I make it so that only the specific submenu toggles its active class when clicked:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function() {
    $("ul li").hover(function() {
      // remove classes from all
      $("nav li:first").toggleClass("active");

    });
  });
</script>

<style type="text/css">
  .container nav li {display: none;}
  .container nav li.active {display:block;}
</style>
<div class="container">
  <ul>
    <li>
      <span>1</span>
      <nav><li>sub 1</li>
      </nav>
    </li>

    <li>
      <span>2</span>
      <nav><li>sub 1</li>
        <li>sub 2</li>
      </nav>
    </li>

  </ul>


</div>

Answer №1

Change the functionality of <nav> to show/hide instead of using <li>. Also, add an active class to the <nav> tag.

Refer to the following code snippet for more details. Modifications have been made in the CSS and jQuery scripts accordingly.

$(function() {
  $("ul li").hover(function() {
    $("nav").removeClass("active");
    // remove classes from all
    $(this).find("nav").toggleClass("active");
  });
});
.container nav{display: none;}
.container nav.active {display:block;padding-left:25px;}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<div class="container">
  <ul>
    <li>
      <span>1</span>
      <nav><li>sub 1</li>
      </nav>
    </li>

    <li>
      <span>2</span>
      <nav>
        <li>sub 1</li>
        <li>sub 2</li>
      </nav>
    </li>

  </ul>


</div>

Answer №2

Adjustment :

$("nav li:first").toggleClass("active");

Modification :

$("nav li",this).toggleClass("active");

Updated code :

$(document).ready(function() {
    
    $("ul li").hover(function() {
        // remove classes from all
        $("nav li",this).toggleClass("active");

    })
    
})
.container nav li {display: none;}
.container nav li.active {display:block;}
<div class="container">
    <ul>
        <li>
            <span>1</span>
            <nav>
                <li>sub 1</li>
            </nav>
        </li>
        
        <li>
            <span>2</span>
            <nav>
                <li>sub 1</li>
                <li>sub 2</li>
            </nav>
        </li>
    </ul>
</div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Answer №3

To achieve this effect, CSS is the only tool you need. Simply follow the code provided below:

HTML:

<div class="container">
    <ul>
      <li>
          <a href="#">menu1</a>
            <nav>
            <li>sub 1</li>
            </nav>
      </li>
      <li>
          <a href="#">menu2</a>
            <nav>
                 <li>sub 1</li>
                 <li>sub 2</li>
            </nav>
      </li>
    </ul>
</div>

CSS:

li{
    transition:0.3s ease-In-Out;
    cursor:pointer;
}
.container nav li {
    display: none;
}
.container nav li.active {
    display:block;
}
ul li:hover nav li{
    display:block;
}

For a live demonstration, please visit this link: https://jsfiddle.net/1235aamp/

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

Top method for stacking several divs in a vertical line

In search of the most effective method for organizing numerous dynamically generated divs (all with identical widths) in a vertical stack, two potential solutions have emerged: Utilize float:left... Implement an unordered list and enclose each div within ...

Tips for incorporating tool-tips into a vertical grouped bar chart using d3 js

I have successfully created a simple vertical grouped bar chart using the code provided below. Now, I want to enhance it by adding tooltips that display specific data about each bar when hovered over. Can anyone assist me with this? Any help is greatly app ...

Creating a personalized cursor transition with CSS styling

I have an unordered list (ul) with items on each list item (li) having a different cursor. While it works fine, the transition is not smooth. Is there a way to make the transition from the default cursor to a custom image smoother? HTML <section class ...

Safari 7.0 Experiencing Unpredictable Ajax Errors

Encountered an issue with Ajax requests through jQuery on a web app while using Safari 7.0 for Mac OS X 10.9 Mavericks (specifically 9537.71). This problem was occurring intermittently and could not be reproduced consistently on Safari 7.0. Environment: ...

Could not find the element using the specified cssSelector

I am attempting to locate and interact with this specific div element. <div class="leaflet-marker-icon marker-cluster marker-cluster-small leaflet-clickable leaflet-zoom-animated" style="margin-left: -6px; margin-top: -6px; width: 12px; height: 12px; o ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

How can I monitor the "OnMouseNotMoving" event using jQuery?

Recently, I had an idea to add a fun feature for users on a webpage - displaying a layer at the mouse position when the user is not moving it, and then hiding it once the mouse starts moving again after a delay. I've managed to figure out the delay u ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Combining Files in Angular 2 for Optimal Production Deployment

What is the best method for packaging and combining an Angular 2 application for production? My goal is to have an index.html file and a single app.min.js file. Although the Angular 2 documentation mentions using webpack, I found it to be overly complex f ...

What events occur before they are detectable in JavaScript?

Below is a code snippet for handling events related to an image: HTML <!DOCTYPE html> <html> <head> <title>Image Event Handling</title> </head> <body> <img src="someImagePath.jpg" class="img-1"/> &l ...

What is the best way to set breakpoints on Material UI components?

Currently, I am exploring material-ui and I'm curious if there is a way to set all breakpoints at once. The code snippet below seems quite repetitive. Is there a more efficient method to achieve this? <Grid xs={12} sm={12} md={12} lg={12} xl={12} ...

Inject JSON data into a jQuery plugin

Currently, I am exploring how to input settings into an animation plugin in the format below (I understand it may not be user-friendly to require users to tinker with settings like this, but a GUI will be developed alongside it): $('#animationContain ...

The parent div's height is not compatible with the CSS grid

I created a CSS grid layout featuring a header, side menu, and scrollable content. My goal is to test this layout in a container div where I've specified the width and height. The layout adjusts well according to the container's width, but seem ...

How do I enable alt text visibility for images in my WordPress theme Kallyas?

I am currently in the process of making my company's website more inclusive by ensuring all images have proper alt text. However, I am facing a challenge in seeing the alt text that I add through the WordPress CMS when viewing the HTML code. Please re ...

The Jquery Click Event does not seem to function properly when applied to a Kendo Grid

I need to implement a jQuery function on the Destroy button in order to store data in an array: For this purpose, I am utilizing Kendo Grid as shown below: @(Html.Kendo().Grid(Model) .Name("Passenger") .TableHtmlA ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

Using jQuery to highlight the navigation menu when a specific div scrolls into view

I have implemented a side navigation consisting of circular divs. Clicking on one scrolls you to the corresponding .block div, and everything functions correctly. However, I am now curious if it is feasible to highlight the relevant .nav-item div based on ...

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

The problem with the Image Gallery carousel not functioning properly in a right-to-left direction arises when attempting to modify

I have been developing an image gallery that functions perfectly in the English version of the website. Now, I am tasked with replicating the same functionality for another version of the website that requires right-to-left (RTL) direction. However, when I ...