Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine when an user is typing

I am building a search box (input field) which should make a server call to filter a grid with the text being inserted on it but I need to make this in an smart way, I need to fire the server call only if the user has stopped. Right now I'm trying to implement it, but if someone knows how to do it I'll be very pleased. Anyway, if I do it first I'll post the answer here... Best Regards, Jaime.

like image 324
Jaime Febres Avatar asked Dec 11 '08 16:12

Jaime Febres


People also ask

How do you know when someone stops typing?

One possible way is to attach a keyup event to the input element and send an HTTP request for each character entered to the server to fetch search results: const input = document. querySelector('#input-text'); // Listen for `keyup` event input. addEventListener('keyup', (e) => { const text = e.


1 Answers

  1. When a key is pressed:
    1. Check if there's an existing timer - stop it if there is one
    2. start a timer.
  2. When the timer expires, call the server method.
var searchTimeout;
document.getElementById('searchBox').onkeypress = function () {
    if (searchTimeout != undefined) clearTimeout(searchTimeout);
    searchTimeout = setTimeout(callServerScript, 250);
};
function callServerScript() {
    // your code here
}
like image 77
nickf Avatar answered Sep 22 '22 01:09

nickf