Add delay to mouseleave in jquery

I use this code on my site and I was wondering how to add a delay to the mouseleave function.

$target.mouseenter(function(e){
                var $tooltip=$("#"+this._tipid)
                ddimgtooltip.showbox($, $tooltip, e)
            })
            $target.mouseleave(function(e){
             var $tooltip=$("#"+this._tipid);
             setTimeout(function() { ddimgtooltip.hidebox($, $tooltip); }, 4000);
            })

            $target.mousemove(function(e){
                var $tooltip=$("#"+this._tipid)
                ddimgtooltip.positiontooltip($, $tooltip, e)
            })
            if ($tooltip){ //add mouseenter to this tooltip (only if event hasn't already been added)
                $tooltip.mouseenter(function(){
                    ddimgtooltip.hidebox($, $(this))
                })
+5
source share
4 answers

The only problem with the timer will be if you click the mouse and then re-enter it, it will still be hidden after this timer ends. Something like the following may work better, because we can cancel the timer whenever the mouse enters the target.

var myTimer=false;
$target.hover(function(){
    //mouse enter
    clearTimeout(myTimer);
},
function(){
    //mouse leave
    var $tooltip=$("#"+this._tipid);
    myTimer = setTimeout(function(){
        ddimgtooltip.hidebox($, $tooltip);
    },500)
});
+10
source
(function($){
   $.fn.lazybind = function(event, fn, timeout, abort){
        var timer = null;
        $(this).bind(event, function(){
            timer = setTimeout(fn, timeout);
        });
        if(abort == undefined){
            return;
        }
        $(this).bind(abort, function(){
            if(timer != null){
                clearTimeout(timer);
            }
        });
    };
})(jQuery);


$('#tooltip').lazybind(
    'mouseout',
    function(){
        $('#tooltip').hide();
    },
    540,
    'mouseover');

http://www.ideawu.com/blog/2011/05/jquery-delay-bind-event-handler-lazy-bind.html

+4
source

setTimeout() :

$target.mouseleave(function(e){
 var $tooltip=$("#"+this._tipid);
 setTimeout(function() { ddimgtooltip.hidebox($, $tooltip); }, 250);
})

250 , , .

+2

, :

$.fn.hoverDelay = function(handlerIn, handlerOut, delay) {
    if(delay === undefined) delay = 400;
    var timer;
    this.hover(function(eventObject) {
        clearTimeout(timer);
        handlerIn.apply(this,eventObject);
    }, function(eventObject) {
        timer = setTimeout(handlerOut.bind(this, eventObject), delay);
    });
};

It works the same as a normal one $.hover, except that there is a delay of 400 ms before the mouse event is fired (which is canceled if you move the mouse backward during this timeframe).

0
source

All Articles