Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Do processing when user has stopped typing

I have a text box on a web page, whose value I want to send to a XMLHttpRequest. Now I want the user to just type the value, without pressing a button. But If i just send the request int he keyboard events, it will fire every time a key is pressed.

So basically I want something liek this

function KeyUpEvent()
{
  if (user is still typing)
    return;
  else 
    //do processing
}

It would be great if the solution could come from plain javascript or mootools. I dont want to use any other library.

like image 534
Midhat Avatar asked Mar 21 '10 18:03

Midhat


2 Answers

The way this is usually done is by restarting a timer on the keyup event. Something like this:

var keyupTimer;
function keyUpEvent(){
   clearTimeout(keyupTimer);
   keyupTimer = setTimeout(sendInput,1000); // will activate when the user has stopped typing for 1 second
} 

function sendInput(){
    alert("Do AJAX request");
}
like image 51
cmptrgeekken Avatar answered Sep 30 '22 17:09

cmptrgeekken


Basically, you want to start a timer on KeyUp, and when KeyUp starts again, reset the timer. When the user stops typing, the timer runs out, and your request can go at that point.

Example:

var timout_id;

function keyup_handler(event) {
  if (timout_id) {
    clearTimeout(timout_id);
  }

  timout_id = setTimeout(function(){
    alert('sending data: \n' + event.target.value)
  }, 800);
}

Just attach the function to the input using your preferred method, and replace the alert with your preferred action.

Of course there are many ways you could generalize this approach and make it more reusable, etc, but I think this illustrates the basic idea.

like image 39
Avi Flax Avatar answered Sep 30 '22 18:09

Avi Flax