Monday, March 19, 2012

Helpful Hints: Javascript/jQuery Knowing When the User Stopped Typing

This is just going to be a quick post with something on my mind to help new coders out there. Really I just need a short break from thinking.
Ever seen those handy dandy sites that preform some action AFTER you finish typing, rather than slowing down your device by trying to repeat the action for every character? Wanna know how to do it? GOOD! Then you're in the right place. This "type waiting" is actually very easy! It's all about timing ... or timers rather.
The one flaw to the following system is being unable to know the average type speed of a user. This is often countered by simply using a 2 second timer (although many sites use only a 1 second timer and preform fine). Two seconds is optimal because it is both: an easy amount of time that most people don't mind waiting to see a reaction, and is usually plenty of time to decide if even a "hunt 'n peck" user has stopped typing. However, you will only know what works best for your sight through experimentation. Now, who wants code?
On with the code! First I will example this action in javascript (hang on jQuery users, you're next) as it is really quite simple and will help you get a better idea of what is going on. The first thing you need to do is create a variable outside of your functions (preferably global, but its up to you, how, when, and where you want to use it). It doesn't have to be anything fancy, but be careful of name-spacing as per usual.
Ok, now that the hard part is over let's create our initial function.
Finally the really easy part, your WORK! Simply write the function you want called after the typeing timer stops!
With all the functions made, the rest is too easy. Simply find the element you want to attach it too. And viola! You're all done!
Now, for those of you using jQuery:
Create your variable. Then the code (even easier, cause its jQuery :D)

Enjoy!

No comments:

Post a Comment