2011-05-27

jQuery Delay Bind Event Handler(Lazy Bind)

Views: 19227 | 1 Comment

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

View: Demo

// 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);


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

@Parameters

  • event: string, event to bind to
  • fn: function, callback
  • timeout: int, time to wait before fn being called, in millisecond
  • abort: string, on which event the binding will be cancelled.
Posted by ideawu at 2011-05-27 16:40:48 Tags: ,

One Response to "jQuery Delay Bind Event Handler(Lazy Bind)"

  • A little modification…

    (function($){
    $.fn.lazybind = function(types, fn, timeout, abort){
    var timer = null;
    if (abort !== undefined){
    $(this).bind(abort, function(){
    clearTimeout(timer);
    });
    }
    return $(this).bind(types, function(event){
    var data = {
    event: event,
    element: this
    };
    timer = setTimeout(function(){
    fn.call(data.element, data.event);
    }, timeout);
    });
    };
    })(jQuery); Reply

Leave a Comment