How to monitor multiple items using the mouseleave event in jQuery

I am currently trying to achieve a specific effect by keeping the green border visible for the active menu item when hovering over the dropdown. The issue I am encountering is that the border disappears when moving the cursor over the dropdown, which is not the desired behavior.

https://i.sstatic.net/S7rJA.gif

Below is the current JavaScript code responsible for handling the border animation:

var menu      = $('.indication'),
    indicator = $('<span class="indicator"></span>');

menu.append(indicator);

menu.find('.has-dropdown, .login-status').mouseenter(function() {
    position_indicator($(this));
});

$('.navigation-wrapper .navi, .dropdown-wrapper').mouseleave(function() {
    indicator.stop().animate({
        left: 0,
        width: 0
    }, 150, function() {
        // Animation complete
    });
});

function position_indicator(el) {
    var left = el.position().left + 20;
    var width = el.width();
    indicator.stop().animate({
        left: left,
        width: width
    }, 150, function() {
        // Animation complete
    });
}

The above code functions correctly for the .navigation-wrapper .navi element and the border disappears as expected on mouseleave. However, my goal is to maintain the border when hovering over the .dropdown-wrapper as well. I have attempted following a similar approach described in How to detect mouseleave() on two elements at once?, but have been unsuccessful in implementing it in my case.

For reference, here is the relevant HTML structure:

<div class="navi-wrapper">
    <nav class="row navigation">
        <div class="navigation-wrapper indication">
            <ul class="navi">
                (Menu items with links)
             </ul>
        </div>
    </nav>
</div>

<div class="dropdown-wrapper">
     <ul id="1" class="dropdown">
         ...
     </ul>

     <ul id="2" class="dropdown">
         ...
     </ul>

     <ul id="3" class="dropdown">
         ...
     </ul>

     <ul id="4" class="dropdown">
         ...
     </ul>

</div>

Answer №1

Make sure to carefully review the comments in the code. The issue with your code arises from it triggering when the mouse moves away from the .navi element. It's important to note that jQuery selectors do not combine separate elements. To resolve this, a workaround is implemented where we check if the mouse is currently hovering over the dropdown. If it is, then we attach the removal of the indicator to when the cursor leaves the dropdown area.

$('.navigation-wrapper .navi').mouseleave(function() {
    // Locate the dropdown
    var $dropdown = $(".dropdown-wrapper");
    // Remove any previous event bindings
    $dropdown.off("mouseleave.indicator");
    // If the mouse is hovering over the dropdown, delay the animation until it exits
    if($dropdown.is(":hover")){
        $dropdown.one("mouseleave.indicator", function(){
            indicator.stop().animate({
                left: 0,
                width: 0
            }, 150, function() {
                // Animation completed
            });
        });
    }
    // If the mouse is not over the dropdown menu, execute the animate out immediately
    else{
        indicator.stop().animate({
            left: 0,
            width: 0
        }, 150, function() {
            // Animation completed
        });
    }
});

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

Choose an image depending on the title, but only if a specific condition is met

var no_images2 = $j("img[title^='Click to enlarge image no_photo']").parent(); $j(no_images2).css('pointer-events','none'); var no_images3 = $j("img[title^='Click to enlarge image no_photo']").parent(); $j(no_images ...

Guide to displaying database results in an HTML dropdown menu by utilizing AJAX technology

Greetings! As a newcomer to the realms of PHP and AJAX, I am currently on a quest to showcase the outcomes of a query within an HTML dropdown using AJAX. Let's delve into my PHP code: $pro1 = mysqli_query("select email from groups"); I made an attemp ...

Alerts for drop down menu validation with multiple buttons

My goal is to design a multi-step form that collects user information. This form consists of 5 stages: Step 1: User details (Name, email, phone, age, gender) Step 2: Yes or No question Step 3: Yes or No question Step 4: Yes or No question Step 5: Yes o ...

What is the best way to reinitialize a particular input field by using either the entered value or the total sum from buttons?

I successfully created a functional sum amount and reset button for a specific field that works perfectly outside of a form tag. However, I now need to place all the input fields and buttons inside a form tag to enable validation before submission. The de ...

Creating Transparent Rounded Backgrounds in Google Chrome Packaged Apps: Achieving the same look as Google Hangout app

Looking at the screenshot below, it is evident that the Hangout app has a fully transparent design with background shadow effect applied to it. I have tried various methods in vain, such as applying CSS styling to the "html" and "body" tags of the page, a ...

`Loading CSS files in Node.js with Express``

My CSS isn't loading properly when I run my HTML file. Even though the HTML is correctly linked to the CSS, it seems like express and node.js are not recognizing it. I find it confusing to understand the articles, tutorials, and stack overflow questio ...

Element does not cross both explicit and implicit columns

When working in a grid container with only 1 column and 1 row, if there is an implicit column in the first row, how can an element in the second row (as shown by the green column in the example) span across both the explicit and implicit columns? I appreci ...

Using the Upload feature in ReactJS

I have been searching high and low for assistance in creating a component within React that can handle file uploads to a specific endpoint I have established. I have experimented with various options, including trying to integrate filedropjs. However, I u ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

Tips for resolving issues with media queries in CSS

After deciding to create both desktop and mobile versions of my site, I attempted to utilize media queries in CSS. Unfortunately, after coding them, I discovered that they were not functioning as expected. Seeking a solution, I turned to Youtube where I ca ...

Ways to isolate and limit the application of CSS in React and Gatsby to specific pages instead of having it affect the global scope

At the moment, I'm working on integrating a keen-slider library(https://www.npmjs.com/package/keen-slider). To install it, we have to include import 'keen-slider/keen-slider.min.css'. This essentially adds the CSS globally to our project. Ho ...

How about using a circle inset clip path technique?

Can a unique inset circle clip path be created to cut a hole through the center of a div instead of just showing the center? The entire div should be visible except for a hole cut out in the center to achieve a design similar to this: https://i.sstatic.n ...

"Adding a next button to a jQuery mobile detail page is a simple process that can

Is it possible to add a "next" button on a detail page in order to navigate to the next detail page? I am new to jqm and wondering if there is a way to achieve this without requesting json data on every page load. Any suggestions or solutions would be grea ...

A 2x2 Bootstrap grid that spans the full height of the viewport, where each cell has vertical overflow set to auto

I need help creating a grid with 100% height that has the following layout: The second row should expand to fill the remaining vertical space, even if cells C & D have limited content. Additionally, if the content in cell D is too large, I want a ver ...

What is the process for making the default text in a text box appear grayed out?

Hey there! I have this cool idea for a text box. Basically, it starts off with default text but when you hover your mouse over it, the text disappears and you can start typing as usual: If you want to see how it looks like, you can check out this link: N ...

Tips for aligning an inline form in Bootstrap 5

I am looking to create an inline form with rows. Each row should include an input field that spans 5 columns, along with a button wrapped in content. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta ...

Modify the width of the <nz-date-picker> component from Ng-Zorro

Currently using Ng-Zorro for my template styling and working on implementing a date picker that I want to align perfectly with the dropdown menu above it. I would like to adjust the width of the date-picker manually within the template, but after visiting ...

What is the best method to detect a change in scroll position on a webpage using JavaScript?

Is there a way to trigger an event when the page's scroll position changes? I'm interested in creating a dynamic table of contents similar to (where the active item changes as you scroll). Can this be achieved without directly accessing the cu ...

Sending multiple PHP arrays as part of an AJAX response

I have been attempting to send multiple arrays in an Ajax request response (get), but have been struggling to achieve it. Here is the PHP code I want to include in the Ajax request response: echo json_encode($catdata); echo json_encode($productdata); ech ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...