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

牧云@^-^@ 提交于 2019-12-04 06:55:18

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.

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.

You could try using the jquery hoverintent plugin.

This works for me:

$(".triger").mouseenter(function() {
    $(this).find("popup").fadeIn();
}).mouseleave(function() {
    $(this).find("popup").delay(200).fadeOut();
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!