What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there any alternative methods to achieve this without relying on jQuery?

Answer №1

CSS can be used to display a submenu on hover without the need for JQuery.

.menu-item:hover .sub-menu {display: block;}

To handle multiple submenus, utilize different IDs or classes to show the corresponding submenu under each menu item.

<style>
.menu {
  margin-left: 220px;
}
.menu-item-text {
  display: inline-block;
  margin-top: 18px;
  color: black;
  font-weight: 550;
}
.menu-item-text:hover {
  content: '';
  color: red;
}
.menu-item-text:hover:after {
  content:'';
  display: block;
  border-bottom: 2px solid rgb(15, 1, 1);
  margin-top: 19px;
}
.sub-menu1 {
  background: yellowgreen;
  position: absolute;
  display: block;
}
.sub-menu li {
  white-space: nowrap;
  display: inline;
}
.sub-menu a:before {
  content: '☆';
  top: 2px;
}
.sub-menu a:hover:before, .sub-menu a:focus:before {
  content: '★';
} 

.menu-item:hover .sub-menu {display: block;}

.navigation .sub-menu {
  display: none;
}
.menu-act .menu-item-text  {
  color: red;
}
.sub-menu1 li, .sub-menu1 a {
  display: inline-block;
}
</style>
<body>
    <nav class="navigation">
        <ul class="menu">
          <li class='menu-item' tabindex='0'>
             <span class="menu-item-text menu-act">About HTML</span>
            <ul class='sub-menu'>
                <li>
                 <a href="#">HTML Introduction</a>
                </li>
               <li>
                 <a href="#">Reference Introduction</a>
                </li>
               <li>
                 <a href="#">Examples</a>
                </li>
            </ul>
           </li>
          </ul>
      </nav>
</body>

If you prefer using JQuery, here's how you can achieve a similar effect:

$(".menu-item").on("mouseover", function(){   // Display the submenu on mouse hover
$(".sub-menu").show();
});

$(".menu-item").on("mouseout", function(){ // Hide the submenu when mouse leaves the menu item
$(".sub-menu").hide();
});
.menu {
  margin-left: 220px;
}
.menu-item-text {
  display: inline-block;
  margin-top: 18px;
  color: black;
  font-weight: 550;
}
.menu-item-text:hover {
  content: '';
  color: red;
}
.menu-item-text:hover:after {
  content:'';
  display: block;
  border-bottom: 2px solid rgb(15, 1, 1);
  margin-top: 19px;
}
.sub-menu1 {
  background: yellowgreen;
  position: absolute;
  display: block;
}
.sub-menu li {
  white-space: nowrap;
  display: inline;
}
.sub-menu a:before {
  content: '☆';
  top: 2px;
}
.sub-menu a:hover:before, .sub-menu a:focus:before {
  content: '★';
} 

.navigation .sub-menu {
  display: none;
}
.menu-act .menu-item-text  {
  color: red;
}
.sub-menu1 li, .sub-menu1 a {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
        <nav class="navigation">
            <ul class="menu">
              <li class='menu-item' tabindex='0'>
                 <span class="menu-item-text menu-act">About HTML</span>
                <ul class='sub-menu'>
                    <li>
                     <a href="#">HTML Introduction</a>
                    </li>
                   <li>
                     <a href="#">Reference Introduction</a>
                    </li>
                   <li>
                     <a href="#">Examples</a>
                    </li>
                </ul>
               </li>
              </ul>
          </nav>
    </body>

jQuery provides mouseover and mouseout or mouseleave events for such interactions.

Answer №2

If you prefer using CSS, that's also an option, but since you mentioned wanting to use jquery, I have provided a solution using JQuery.

Here is the code snippet that I believe meets your requirements:-

$(document).ready(function(){
  $('.menu-item-text').mouseover(function(){
    $(this).next('.sub-menu').show();
  });
  $('.menu-item-text').mouseout(function(){
    $(this).next('.sub-menu').hide();
  });
});
.menu {
  margin-left: 220px;
}
.menu-item-text {
  display: inline-block;
  margin-top: 18px;
  color: black;
  font-weight: 550;
}
.menu-item-text:hover {
  content: '';
  color: red;
}
.menu-item-text:hover:after {
  content:'';
  display: block;
  border-bottom: 2px solid rgb(15, 1, 1);
  margin-top: 19px;
}
.sub-menu1 {
  background: yellowgreen;
  position: absolute;
  display: block;
}
.sub-menu li {
  white-space: nowrap;
  display: inline;
}
.sub-menu a:before {
  content: '☆';
  top: 2px;
}
.sub-menu a:hover:before, .sub-menu a:focus:before {
  content: '★';
} 
.navigation .sub-menu {
  display: none;
}
.menu-act .menu-item-text  {
  color: red;
}
.sub-menu1 li, .sub-menu1 a {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navigation">
    <ul class="menu">
      <li class='menu-item' tabindex='0'>
         <span class="menu-item-text menu-act">About HTML</span>
        <ul class='sub-menu'>
            <li>
             <a href="#">HTML Introduction</a>
            </li>
           <li>
             <a href="#">Reference Introduction</a>
            </li>
           <li>
             <a href="#">Examples</a>
            </li>
        </ul>
       </li>
      </ul>
  </nav>

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

Tips for transferring data using the GET method from the client side to the server side via AJAX

I am attempting to send two dates - a start date and an end date, in order to retrieve data between those two dates. However, my current implementation is not working as expected. $(document).ready(function(){ const date_inputs = new FormData(); ...

Spinning a div using Jquery

I'm having trouble getting a div to rotate. Despite checking the console, I haven't encountered any warnings or errors. If you'd like to see the JSFiddle version of it, feel free to take a look. Below is the code snippet I've been usi ...

Issue with collecting data in Meteor Collection

After making some edits to another file and increasing the complexity of my application, a tracker function that was previously working fine is now experiencing issues. It is no longer returning any data for vrLoan fundingData This is a snippet of my c ...

Vue component fails to trigger upon receiving the 'mouseleave' event

I am currently working on a navbar with dynamic component navigation, where hovering over a navbar-link should display the corresponding component and hiding it when the mouse leaves. Although the components are displayed correctly upon hover, they do not ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

Utilizing a JavaScript class method through the onchange attribute triggering

I am facing an issue with a simple class that I have created. I can instantiate it and call the init function without any problems, but I am unable to call another method from the onchange attribute. Below is the code for the class: var ScheduleViewer = ...

Knockout JS: Choosing specific dropdown elements

My array doorsForSite contains a list of doors, each with its own set of schedules. Here is how it looks: var scheduleList = new[] { new { ScheduleId = "Schedule1",ScheduleName = "Always On" }, new ...

Incorporate JSON information into HTML dropdown menu using Google API

I'm finding it difficult with this task. Below is a list that needs the name and address inserted into the dropdown menu from the JSON file. <div class="dropdown-list"> <div class="list-container"> <ul class="list" ...

What is the functionality of Vue plugins in Vite MPAs?

I have developed a Vite application and I am trying to implement multiple pages. I followed the documentation on how to achieve this (link here), but when I start the server, all I see is a blank page. This is what my vite.config.js file looks like: impor ...

Create bubble diagrams to display detailed information within a line graph using Chart.js

After creating a line chart with chartJS, I am looking to enhance it by adding bubbles to indicate specific data points such as the mode, red, and amber levels. While I have successfully drawn the lines on the chart, I am unsure of how to incorporate these ...

Tips for including numerous hyperlinks in a single row for a website's navigation menu

I need assistance in creating a navigation bar for my website that includes multiple headers with links. I am not sure if the issue lies within my CSS, HTML, or both. Can someone please help me troubleshoot? index.html <!DOCTYPE html> <html> ...

jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achi ...

Extract data from JSON array using jQuery and display as comma-separated values

Is it possible to extract specific values from a JSON array and then output only the IDs in a certain format? [{"id":1,"name":"Blue"}, {"id":2,"name":"Green"}, {"id":3,"name":"Red"}] The desired output is: ['1','2','3',&apo ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

Angular Flot Chart Resizing: A Guide to Dynamic Chart S

I have successfully integrated a Flot chart into my HTML using an Angular directive. Here is how it looks: <flot id="placeholder" dataset="dataset" options="options" height="300px" width="100%" style="width:100%;" ng-disabled="graphLoading" ng-class="{ ...

conflict between ng-content and textarea elements

My custom component called my-textarea has a unique template structure: <textarea> <ng-content></ng-content> </textarea> However, when I try to input text into the component using the same method as a regular textarea HTML eleme ...

How to Retrieve HTML Content from an Azure Function Using C#

I created an Azure function using C# that generates HTML content. However, when I access it from a web browser, the response is displayed as plain text instead of rendering as HTML. After some research, it seems like I need to define the ContentType header ...

"What is the best way to move a cloned image after it has been dropped

I am facing an issue with image dragging after rotating it. The problem is that I am unable to drag the image for the first time when it is dropped. Below is the code for image drag and drop using "dhtmlgoodies_xpPane li .rotatable". I can successfully dra ...

Adjust the horizontal background-position transition for color change while scrolling using jQuery and CSS

I came across a fascinating website - - where the background-position changes on scroll() from a linear gradient with two colors to smoothly slide one color off the screen. While I grasped how they achieved the split colors using linear-gradient, I'm ...