case
11Aug/106

On typing finished jQuery plugin

If you are developing a form and you require certain validations; check if username is available or not for example - the way to do that is to listen for the change/focusout DOM events. You can also check it on every keypress but if the validation does some expensive checking in the background that is out of the question. So here is a really small jQuery plugin that does tell you when a user finished typing inside a text box. The way it does it is to compute the speed the user is typing with and when a delay longer than twice the speed average occurs, the event is triggered and your validation function is called. Simple enough.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function () {
  $.fn.onTypeFinished = function(func) {
     var T = undefined, S = 0, D = 1000;
     $(this).bind("keypress", onKeyPress).bind("focusout", onTimeOut);
     function onKeyPress() {
        clearTimeout(T);
        if (S == 0) { S = new Date().getTime(); D = 1000; T = setTimeout(onTimeOut, 1000); return; }
        var t = new Date().getTime();
        D = (D + (t - S)) / 2; S = t; T = setTimeout(onTimeOut, D * 2);
     }
 
      function onTimeOut() {
           func.apply(); S = 0;
      }
      return this;
   };
});

The way to use it:

1
$("input[name='username']").onTypeFinished(myValidationFunction)

And here is a small demo:

Related posts:

  1. jQuery.quickEach
  2. Parse XML in JavaScript with jQuery
  3. For Javascript devs
  4. Serialize JavaScript object to JSON
  5. Open and Save files to Desktop without going to Server
Comments (6) Trackbacks (0)
  1. Cool Just what I needed
    thanks

  2. This is great. Nice work mate!

  3. this is awesome! very smart solution to the problem.

  4. as nice as simple! thanks!

  5. backspace dosent work on chrome 10.0.
    but works correctly on ff


Leave a comment


*

CommentLuv badge

No trackbacks yet.