Javascript: handle when a user stops typing

I have a text box on a webpage whose value I want to send to XMLHttpRequest. Now I want the user to simply type in a value without pressing a button. But if I just send a request for keyboard events, it will fire every time I press a key.

So basically I want to do something this

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

It would be great if the solution came from simple javascript or mootools. I do not want to use any other library.

+5
source share
7 answers

This is usually done by restarting the timer in the event keyup. Something like that:

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");
}
+9
source

, KeyUp, KeyUp , reset . , , .

:

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);
}

, , alert .

, , .., , .

+9

, , :

var typewatch = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  }  
})();

( MooTools):

$('textInput').addEvent('keyup', function(e){
  typewatch(function () {
    // executed only 500 ms after the last keyup event
    // make Ajax request
  }, 500);
});

, typewatch, , . , ( ).

+5

, "" . , .

, - , (cf. window.setTimeout(...)), , . "key-up", .

+2
var keyTimer;
function onKeyUp(){
clearTimeout(keyTimer);
setTimeout(stoppedTyping,1500);
}
function stoppedTyping(){
// Profit! $$$
}

: -

+1

jQuery, :

jQuery.event.special.stoppedtyping = {
  setup: function(data, namespaces) {
    jQuery(this).bind('keyup', jQuery.event.special.stoppedtyping.keyuphandler);
  },
  teardown: function(namespaces) {
    jQuery(this).bind('keyup', jQuery.event.special.stoppedtyping.keyuphandler);
  },
  keyuphandler: function(e) {
    var interval = 1000;
    var el = this;

    if (jQuery.data(this, 'checklastkeypress') != null) {
      clearTimeout(jQuery.data(this, 'checklastkeypress'));
    }

    var id = setTimeout(function() {
      jQuery(el).trigger('stoppedtyping');
    }, interval);
    jQuery.data(this, 'checklastkeypress', id);
  }
};

:

$('input.title').bind('stoppedtyping', function() {
  // run some ajax save operation
});

- .live(...). , ...

0

onBlur , , onKeyDown, , return/enter.

-1

All Articles