Jquery: How to add a delay to mouseleave so if someone accidentally hovers off the element unintentionally, it still stays open

android.nick picture android.nick · Jan 28, 2011 · Viewed 9.5k times · Source

THE hoverintent plugin is the opposite of what I need. I have a .popup that is triggered by .trigger, when i hover off of it, i want .popup to NOT fadeout for a few seconds, but if I hover off, then hover on again, cancel the fadeout that was going to happen and keep the .popup open.

Does anyone know how I would do this?

This DOESN'T work, but it was an idea:

 $('.trigger').hover(function(){
        $('.popup').fadeIn(600)
    }, function() {
        $('.popup').delay(2000, function(){
            if ($(this).blur() = true) {
                $('.popup').fadeOut(600)
            }
        });
    })

Answer

stephen776 picture stephen776 · Jan 28, 2011

the jQuery HoverIntent plugin is exactly what your looking for.

The timeout property will set the amount of time the mouse needs to be OUT of the area before the out function is called.

Quote from the hover intent website:

timeout: A simple delay, in milliseconds, before the "out" function is called. If the user mouses back over the element before the timeout has expired the "out" function will not be called (nor will the "over" function be called). This is primarily to protect against sloppy/human mousing trajectories that temporarily (and unintentionally) take the user off of the target element... giving them time to return. Default timeout: 0

To set it up...

$('.trigger').hoverIntent({
     over: startHover,
     out: endHover,
     timeout: 2000
});

Then define the functions to handle over and out

 function startHover(e){
    //your logic here
    $('.popup').fadeIn(600)
 }

 function endHover(){
     //your logic here
     $('.popup').fadeOut(600)
 }

EDIT:

You can also adjust the interval property to increase/decrease the amount of time for the startHover function to fire...the default is set to 100 milliseconds...you can set it to zero to fire off the popup as soon as the mouse enters the trigger area if youd like.