Reputation: 28384
I have an input on an HTML page where a person will type something and what I'm wanting is for a function to be called every time they stop typing. I know about the onkeypress event, but that is called every time a character is typed. Here's an example of what I would like:
Is this possible?
Thanks a lot!
Upvotes: 5
Views: 2768
Reputation: 32273
Listen to onkeyupevent. There start a timeout (you have to define "stop" as some time amount, otherwise it will be called at every keyup), and in the timeout execute your function.
If onkeydown is called while your timer is running, stop it.
Something like...
var timer;
function onKeyUpHandler(e){
timer = setTimeout("foo()", 500)
}
function onKeyDownHandler(e) {
clearTimeout(timer);
}
How this code exactly looks depends where and how you are using it... just to show the way to do it.
Upvotes: 11
Reputation: 3786
If I understand well, "stop typing" means "no keystrokes for a certain amount of time". In this case, you have to use timers : http://jsfiddle.net/xnghR/1/
Upvotes: 0
Reputation: 1990
First, capture the "key up" event, and set a "stoppedTyping" variable to true. Then set a timer (how long you want to wait before considering this a "stopped typing" event).
If, before the timer goes off, you capture a "key down" event, set "stoppedTyping=false"
When the timer goes expires, your timer callback can check the value of "stoppedTyping". If it's true, then the user has stopped typing (or more precisely, has not typed any new chars for the duration of your timer). If it's false, then they have not stopped typing -- they must have typed at least one more char while your timer was running.
Upvotes: 0
Reputation: 36
Just set a javascript timer to start/restart on onKeyPress. Then just define how long defines "stops typing" and run your script.
Upvotes: 0