Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add delay to mouseleave in jquery

Tags:

jquery

I'm using this code in my site and I was wondering how I could 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))
                })
like image 443
Dustin McCarthy Avatar asked Sep 14 '10 13:09

Dustin McCarthy


2 Answers

The problem with just a timer would be if you mouse left and then re-entered it would still hide after that timer completed. Something like the following might 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)
});
like image 129
FiniteLooper Avatar answered Sep 26 '22 21:09

FiniteLooper


(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

like image 38
ideawu Avatar answered Sep 26 '22 21:09

ideawu