Issue encountered with jQuery nested hover events and the removeClass() function being triggered on mouseleave

I have a nested list structure that I am working with:

<ul class="menu-wrapper">
    <li>
        <a href="#">Menu item</a>
        <ul class="sub-menu">
            <li>
                <a href="#">Subitem-1</a>
                <ul>
                    <li>Sub-Subitem-1</li>
                    <li>Sub-Subitem-2</li>
                    <li>Sub-Subitem-3</li>
                </ul>
            </li>
            <li>
                <a href="#">Subitem-2</a>
                <ul>
                    <li>Sub-Subitem-1</li>
                    <li>Sub-Subitem-2</li>
                    <li>Sub-Subitem-3</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

My current task involves adding and removing the .active class when hovering over certain elements. Here is my existing jQuery code for handling these interactions:

$('ul.menu-wrapper').children().hover(
    function() {
        let subMenu = $(this).find('ul.sub-menu').first()
        subMenu.addClass('active')
        subMenu.children().first().addClass('active')
    },
    function() {
        let subMenu = $(this).find('ul.sub-menu').first()
        subMenu.removeClass('active')
    }
)

Now, I need to enhance this functionality by ensuring that when hovering over li items within the ul.sub-menu, the .active class should be applied dynamically to the hovered item. This requires another hover event on the submenu children:

$('ul.menu-wrapper').children().hover(
    function() {
        ...
        subMenu.children().hover(
            function() {
                $(this).addClass('active')
            },
            function() {
                $(this).removeClass('active')
            }
        )
    },
    function() {
        ...
    }
)

In order to maintain an .active state at all times, even when transitioning between parent and child elements, I need to modify the behavior of the code to ensure that there is always at least one ul.sub-menu > li item with the .active class. Currently, the default behavior removes the class when moving from a submenu back to the parent list item. How can I adjust this to meet the desired outcome?

For a live demonstration, visit: https://jsfiddle.net/5Lwyh3xs/

Answer №1

When the mouse moves out, add the active class to the first list item if no list items have the active class.

$('ul.menu-wrapper').children().hover(
  function() {
    let subMenu = $(this).find('ul.sub-menu').first()

    subMenu.addClass('active')
    subMenu.children().first().addClass('active')

    subMenu.children().hover(
      function() {
        $(this).addClass('active').siblings().removeClass('active')
      },
      function() {
        $(this).removeClass('active')
        if($('.sub-menu > li.active').length == 0) {
             subMenu.children().first().addClass('active')
        }
      }
    )
  },
  function() {
    let subMenu = $(this).find('ul.sub-menu').first()

    subMenu.removeClass('active')
  }
)
body {
  margin: 0;
  padding: 0;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

ul.menu-wrapper {
  height: 80px;
}

ul.menu-wrapper {
  background: gray;
}

ul.menu-wrapper>li {
  height: 100%;
  display: flex;
  align-items: center;
}

ul.menu-wrapper ul.sub-menu {
  visibility: hidden;
  position: absolute;
  top: 80px;
}

ul.menu-wrapper ul.sub-menu.active {
  visibility: visible;
}

ul.menu-wrapper ul.sub-menu.active>li.active {
  background: darkmagenta;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav role="navigation" id="navigation-wrapper">
  <ul class="menu-wrapper">
    <li>
      <a href="#">Menu item</a>
      <ul class="sub-menu">
        <li>
          <a href="#">Subitem-1</a>
          <ul>
            <li>Sub-Subitem-1</li>
            <li>Sub-Subitem-2</li>
            <li>Sub-Subitem-3</li>
          </ul>
        </li>
        <li>
          <a href="#">Subitem-2</a>
          <ul>
            <li>Sub-Subitem-1</li>
            <li>Sub-Subitem-2</li>
            <li>Sub-Subitem-3</li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav>

https://jsfiddle.net/y5qkb7mv/

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

Alter the style of a div by clicking on a button

Can the background image of a div be changed by selecting a button outside of the div? For example: HTML <div id="change"></div> <div id="buttons"> <button class="button1">this</button> <button class="button2"> ...

How to concatenate a string variable to a hyperlink in a template file

Within my project, there is a file named registration_email.tpl that is passed as email_template in the bottle.template() function. This involves passing variables such as username, email_addr, role, creation_date, and registration_code. email_text = ...

Incorporating CSS into an HTML page created by a Python CGI script

Last week, I was handed a Python-based monitoring and notification tool to work on. My task is to develop a proof of concept dashboard using the data collected by this tool over the years. The catch is that I'm fairly new to Python and have never dabb ...

Determine the height of an image using JavaScript

How can I retrieve the height of an image in a JavaScript function? When I use the code: var image_height = $(image).height(); The value of image_height is 0, even though my image definitely has non-zero height. Is there a different method to accurately ...

Using JQuery to reverse the action of hiding an image

Having some trouble with my Javascript and JQuery skills, so bear with me. I've set up a gallery of images where users can drag and drop them into a designated drop zone. Everything works fine when dragging an image from the gallery to the drop zone a ...

Tips for Adding Items to an Infinite Loop

Could you please review This Demo and advise me on how to continuously load items into the ul list in an endless manner? Currently, I have this code set up to display the list but I want it to keep adding new items to the end every time. var item = $(". ...

Angular 7 - Datatables - File Upload Feature

I'm trying to incorporate an "upload" button into my table: Below is my TS file with dtOption : ... order: [[3, 'desc']], dom: 'Blfrtip', stateSave: true, buttons: [ ...

How to align content in the center horizontally and vertically using HTML and CSS

I'm having trouble centering my content both vertically and horizontally on the page. Can anyone provide assistance? Thank you. <style type = "text/css"> #loginMenu { border:5px solid green; padding:10px 10px 10px 10px; background-color:#FF9; ...

Fetching data from a ColdFusion component using AJAX

Having trouble performing an SQL COUNT on my database using AJAX through a cfc file, and I can't figure out how to retrieve the return variable. Here's the relevant section of the cfc file: <cffunction name="getSpeakerCount" access="remote" r ...

Can you explain the distinction between JQuery and a jQuery Plugin?

There seems to be a bit of confusion around whether it's called simply JQuery or JQuery Plugin. After doing some research, I couldn't find a clear explanation on whether they are the same thing. Can you shed some light on this? ...

Has the jQuery plugin object misplaced a variable?

I am in the process of developing a basic plugin using jQuery. My current approach involves creating private functions and storing variables within the jQuery object itself. (function($) { var somePrivateFn = function() { alert(this.x); } ...

Continuously improving the form as they evolve

I am interested in creating a form that automatically sends data when users make changes to it. For instance: Imagine a scenario where a moderator is editing an article and changes values in a select field. As soon as the change is made, an ajax request ...

`AJAX jQuery for efficient file uploads`

I am struggling to upload a file input using jQuery ajax without causing the page to refresh. Here is my HTML form: <form name="uploadform" id="uploadform" method="post" enctype="multipart/form-data"> <div name="profileBiodata" id="profileBioda ...

Ways to trigger a function when the body is loaded

In this snippet, I am attempting to execute the oauth2_login() function when the body loads, which is intended to log in the user. Currently, I have hardcoded values from the database into the username and password fields. <!DOCTYPE html> <html&g ...

Utilizing Ajax, Jquery, and Struts2 for File Uploading

Can someone please provide guidance on uploading files using a combination of Ajax, jQuery, and Struts2? I have searched through numerous tutorials online but haven't found a suitable solution yet. The goal is to trigger a JavaScript function when a b ...

I am experiencing issues with my bootstrap file not working despite providing the correct file path. The styles are not being applied on my webpage

The file path is provided below <link rel="stylesheet" href="../css/bootstrap.min.css"> I have exhausted all options in an attempt to resolve the issue. The browser console indicates a 404 error (err_abborted) ...

Tips for lining up segmented pictures in HTML?

Recently, I was presented with a set of sliced images to insert into an HTML document. These images were not sliced by me, but rather provided as individual pieces. To showcase these images in a grid-like manner, I opted to construct a table layout. Each r ...

Leveraging the power of HTML5 alongside Angularjs and Node/Express within the MEAN.js boilerplate framework

I've decided to kickstart my app using the mean.js () boilerplate because of its built-in authentication/authorization features. However, I've hit a roadblock when it comes to incorporating HTML5 into my project. In my Angular app, I've en ...

Scrapy spider malfunctioning when trying to crawl the homepage

I'm currently using a scrapy scrawler I wrote to collect data from from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from .. import items clas ...

New feature in Bootstrap 4 beta allows carousel arrows to be positioned outside of the

I created a text-based carousel using Bootstrap 4 beta. Is it possible to move the arrows off of the slider area and position them outside of it? I have tried searching on Google and in other forums, but I couldn't find a solution. The issue is that s ...