Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
            }
        });
    })
like image 816
android.nick Avatar asked Jan 28 '11 17:01

android.nick


2 Answers

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.

like image 53
stephen776 Avatar answered Sep 22 '22 01:09

stephen776


Here's the simplest way to do it, without additional plugins:

$('.trigger').hover(function() {
    clearTimeout(this.timer);
    $('.popup').fadeIn(600);
}, function() {
    this.timer = setTimeout(function() { 
        if ($(this).blur() = true) { // off topic: you should to check this condition ;)
            $('.popup').fadeOut(600);
        }
    }, 2000);
});

setTimeout() and clearTimeout() are native JS functions of HTML DOM Window object since forever.

like image 42
Dejan Milosevic Avatar answered Sep 24 '22 01:09

Dejan Milosevic