jQuery TypingEnd Event


Ever wanted to fire an event when a user stops typing into an input or textarea? Here is a quick jQuery plugin to do just that:

(function($){

    $.fn.extend({
        typingEnd: function(callback, timeout){
            callback = callback || null;
            timeout = timeout || 500;

            return this.each(function() {
                var $t = $(this),
                    elapse_timeout = null;
                if(callback){
                    $t.bind('typingEnd', callback);
                    if(!$t.data('hasTypingEndEvent')){
                        $t.data('hasTypingEndEvent',true);
                        $t.keyup(function(e){
                            if(elapse_timeout) 
                                clearTimeout(elapse_timeout);

                            elapse_timeout = setTimeout(function(){
                                $t.trigger('typingEnd');
                            }, timeout);
                        }); // end keyup
                    }
                }
                else $t.trigger('typingEnd');
            }); // end each
        } // end typingEnd
    }); // end extend

})(jQuery);

Once you include this snippet you can attach events like the following

// pass in the callback function
$myInput.typingEnd(callback);

// if the typingEnd functionality is already bound to the element you can use bind
$myInput.bind('typingEnd', anotherCallback);

It will check if the user has pressed any keys within the given timeout. If not the event is fired.