Monday, April 14, 2008

JQuery Time-Delay Event Binding Plugin

Just to get a sense of how hard it would be I decided to write a plugin for JQuery I didn't see in the core. Basically this is a the same thing as the .bind function for JQuery except that it takes a timing parameter. How is this useful? Say you want do something 'onclick' or 'onchange' except you want to wait X milliseconds first. Perfect for an autocomplete ('onkeyup' I guess you'd use).

I have to say, I really like the JQuery programming model, and I think the author has really hit on something special. The plugin structure lets me write something that encapsulates state, and at the same time gives me a way to use it as if it were a static function. Pow.

Without further ado:

Update [12/10/2008]: The original version of this script didn't pass in the event object like JQuery's event binding. This has now been corrected. Invocation of the plugin stays the same.

----
Javascript:

(function($){
/**
* jQuery delayed event execution.
*/
$.fn.delay = function(options) {
var timer;
var delayImpl = function(eventObj) {
if (timer != null) {
clearTimeout(timer);
}
var newFn = function() {
options.fn(eventObj);
};
timer = setTimeout(newFn, options.delay);
}

return this.each(function() {
var obj = $(this);
obj.bind(options.event, function(eventObj) {
delayImpl(eventObj);
});
});
};
})(jQuery);

----

Usage:

$(document).ready(function() {
$('#typeinme').delay({
delay: 500,
event: 'keyup',
fn: function(){
alert(this.value);
})
});
}

----
Html:

<form action="#" method="get">
<input id="typeinme" name="station"></input>
</form>