DEV Community

Eddie
Eddie

Posted on

How to detect when the user stops typing

Background

It is common to add keystroke events to input elements to detect when a user is typing such as keypress, keydown, and keyup. But sometimes, these alone are too granular for your needs. Imagine sending a Fetch request to your server to update a DB record after every keystroke!

With just a little bit of code, we can make handling user keystrokes more practical and more performant.

Practical applications

  1. Implement an auto-save feature
  2. Keep your local data store up-to-date
  3. Synchronize the view with real-time collaborators

Here's what you're going to build

Let's define some basic variables

let timer,
    timeoutVal = 1000; // time it takes to wait for user to stop typing in ms

// pointers to our simple DOM elements
const status = document.getElementById('status');
const typer = document.getElementById('typer');
Enter fullscreen mode Exit fullscreen mode

Add two separate event listeners on keypress and keyup

// detects when the user is actively typing
typer.addEventListener('keypress', handleKeyPress);
// triggers a check to see if the user is actually done typing
typer.addEventListener('keyup', handleKeyUp);
Enter fullscreen mode Exit fullscreen mode

Create a timeout on keyup event

// when the user has stopped pressing on keys, set the timeout
// if the user presses on keys before the timeout is reached, then this timeout should be canceled via the keypress event
function handleKeyUp(e) {
  window.clearTimeout(timer); // prevent errant multiple timeouts from being generated
  timer = window.setTimeout(() => {
  status.innerHTML = 'All done typing! Do stuff like save content to DB, send WebSocket message to server, etc.';
  }, timeoutVal);
}
Enter fullscreen mode Exit fullscreen mode

Clear the timeout object on keypress

// when user is pressing down on keys, clear the timeout
// a keyup event always follows a keypress event so the timeout will be re-initiated there
function handleKeyPress(e) {
  window.clearTimeout(timer);
  status.innerHTML = 'Typing...';
}
Enter fullscreen mode Exit fullscreen mode

That's it!

See how simple that was? Now you can make a more accurate determination on when the user has stopped typing and process data more intelligently.

Make it better - other things to think about!

  1. How would you handle Backspace events?
  2. How would you handle version control?

Follow me on Twitter https://twitter.com/eddieaich

Top comments (1)

Collapse
 
salmabader profile image
salmabader

That's really what I'm looking for!

But when I applied the same code to a separate JavaScript file and linked it to HTML, it didn't work :(
Is there any plugins or library that should be included?

Thank you