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

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...

Showing a solo item from an array in HTML using Angular

How can I display the account name instead of the accountId property value from my list of transaction items? I have a list of transactionitems with an accountId property, and all accounts are loaded in the accounts$ array. However, I am having trouble us ...

Having trouble getting my soundboard to work properly on mobile devices

I recently created a soundboard using HTML5, CSS3, and JavaScript. While the audio plays back perfectly on my computer when I click the buttons, I encounter an issue when trying to use it on a smartphone. <!DOCTYPE html> <html lang="en"> <h ...

Capture the JSON data and save it into a separate JSON file

Just starting out with JSON and using an ajax call, I've managed to retrieve a JSON object with the following structure: { data: [ { bouquet: "Interactive", list: [] }, { bouquet: "Movie ...

Transfer the information on the onClick event to the loop's function

When creating my component within the parent component, I follow this approach: renderRow(row){ var Buttons = new Array(this.props.w) for (var i = 0; i < this.props.w; i++) { var thisButton=<FieldButton handler={this.actionFunction} key={&ap ...

The jQuery .load function does not function properly when an ajax query is already underway

My web application utilizes dynamic loading of content within the same div (.content) through either an ajax request or a .load() request. An example of the ajax request code snippet is: $(document).on('click', '.button1', functio ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

The ajax PUT request encounters an internal server error and does not succeed

handleSurprise(userResponse) { // function to handle user's surprise response var updateURL = "/" + serviceContext + "/service/updateinfo/"; var userRespString = JSON.stringify(userResponse); var parsedUserResponse = JSON.parse(userRespS ...

Want to develop a web application and incorporate Ajax into it?

I'm sure many of you have created an online application that streamlines processes and saves time and money for your company. So, how did it go when you added some Ajax to enhance the user experience after developing the application? Any recommendat ...

Before accessing the page, please ensure to make a double request

Encountered a weird issue, While inspecting the network tab in Chrome devtools, I noticed that my Vue app is making double requests to the same endpoint :/ Here's a snippet of my code: In the router section, I have a beforeEach function. When I navig ...

Attempting to modify the information within the #content division of a webpage through the activation of a linked image within a jquery slideshow

I'm completely stuck on this one, even though I'm relatively new to jquery. My goal is to design a webpage where there is a slideshow of products at the top, and when a user clicks on one of the products, it should update the main #content div w ...

Can you conceal a JavaScript function within a specific scope?

Suppose I have two functions a and b that I want to keep within a certain functional scope. Since they share some common code, I decide to extract this shared functionality into another method named support. support should be accessible by both a and b, b ...

A step-by-step guide on how to implement a window scroll-controlled color transition

I've implemented jQuery code to change the opacity of my navbar's background as the user scrolls, transitioning from transparent to blue. Here's the snippet: $(window).scroll(function(){ var range = $(this).scrollTop(); var limit = 45 ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Guide to adjusting margin size according to specific screen size thresholds?

I've set up a series of reactstrap cards that are dynamically organized into rows. On "md" screen sizes and larger (bootstrap), there will be 3 cards per row, while fewer screens will display 2 cards. Here's the component: <Card outline ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...

How can I correct the code that is running both the if and else statements simultaneously?

In the code snippet below, a comparison is made between a username and password. If both are correct, the user is redirected to another page. However, there seems to be an issue where both the if and else statements are executing. Code: if (isset($_POST[ ...

Storing information in Firebase using React.js

When storing an object in Firebase, I expected the structure to be as shown in the image below. However, what I received was a generated running number as a key. This is the code I used to store the object in Firebase: var location = []; location.push({ ...

I'm experiencing issues with event.preventDefault() not functioning properly when used within a contenteditable div

I'm currently working with some basic Angular 7.x code that involves a contenteditable div. I'm attempting to prevent the default action when a user hits the [ENTER] key, but no matter what I do, it still moves the cursor to the next line. What a ...