jQuery JavaScript Lazy Bind or Delay Bind

[Return to article] [Download]

Bind an event handler to one or more elements, allowed to abort the bindation on other event. Usefull for showing tooltip when mouse moves on elements after a few time.

Hello! This is a tool tip.
delay time: ms
mouse over me!

How to use?

Download lazybind.js, or simply copy and paste the codes below to one of you .js files.

// define
(function($){
    $.fn.lazybind = function(event, fn, timeout, abort){
        var timer = null;
        $(this).bind(event, function(e){
            var ev = e;
            timer = setTimeout(function(){
                fn(ev);
            }, timeout);
        });
        if(abort == undefined){
            return;
        }
        $(this).bind(abort, function(){
            if(timer != null){
                clearTimeout(timer);
            }
        });
    };
})(jQuery);

Here is a example of using lazybind.

// example
$('#my_img').lazybind(
    'mouseover',
    function(){
        alert(1);
    },
    500,
    'mouseout');

@Parameters