- π» Wait for User to Stop Typing, in JavaScript
- Step 1. Listen For User Input
- Demo 1 β Output on Every Keystoke
- Step 2. Debounce Event Handler Function
- Demo 2 β Output When Typing Stops
- Element: keypress event
- Syntax
- Event type
- Event properties
- Examples
- addEventListener keypress example
- onkeypress equivalent
- How to detect when the user stops typing
- Practical applications
- Here’s what you’re going to build
- Let’s define some basic variables
- Add two separate event listeners on keypress and keyup
- Create a timeout on keyup event
- Clear the timeout object on keypress
- That’s it!
- Make it better — other things to think about!
- How to detect when the user stops typing in JavaScript
- You might also like.
π» Wait for User to Stop Typing, in JavaScript
Letβs say you have a search feature on your website that you want to live-update while the user types. The naive implementation would be to send a query to your server on every keystroke. This quickly falls apart, however, because users easily type faster than your server can respond. This makes for a poor user experience and created unnecessary load on your server.
A better solution is to execute the search only after the user stops typing. Implementing this is fairly simple once you understand how to debounce a function, which weβll learn in this post.
Step 1. Listen For User Input
To start our demonstration, letβs implement that naive solution mentioned in the introduction. Weβll create an HTML and add an event listener that will be called whenever the inputβs value is changed.
a simple input box --> input type="text" id="my-input" />
// Get the input box let input = document.querySelector('#my-input'); // Add an event listener to monitor changes input.addEventListener('keyup', function (e) console.log('Value:', input.value); >);
Demo 1 β Output on Every Keystoke
Thereβs nothing wrong with performing a console.log on every keystroke, it works just fine and is very performant. However, if that log message was replaced by a slow network call, the server wouldnβt be able to respond quickly enough. On top of that, since the user is still typing, updating the interface to show the results wouldnβt be useful anyway. Letβs fix it.
Step 2. Debounce Event Handler Function
In order to execute an event listener (or any function for that matter) after the user stops typing, we need to know about the two built-in JavaScript methods setTimeout(callback, milliseconds) and clearTimeout(timeout) :
setTimeout is a JavaScript method that executes a provided function after a specified amount of time (in milliseconds). clearTimeout is a related method that can be used to cancel a timeout that has been queued.
So how do we use these things to detect when a user stops typing? Hereβs some well-documented code to demonstrate.
// Get the input box let input = document.getElementById('my-input'); // Init a timeout variable to be used below let timeout = null; // Listen for keystroke events input.addEventListener('keyup', function (e) // Clear the timeout if it has already been set. // This will prevent the previous task from executing // if it has been less than clearTimeout(timeout); // Make a new timeout set to go off in 1000ms (1 second) timeout = setTimeout(function () console.log('Input Value:', textInput.value); >, 1000); >);
Demo 2 β Output When Typing Stops
Typing in the input box above, you can see that nothing is outputted until no key is pressed for 1 secondβexactly what we want. π
If you enjoyed this tutorial, please consider sponsoring my work on GitHub π€
Element: keypress event
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The keypress event is fired when a key that produces a character value is pressed down.
Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don’t produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
Warning: Since this event has been deprecated, you should use beforeinput or keydown instead.
Syntax
Use the event name in methods like addEventListener() , or set an event handler property.
addEventListener("keypress", (event) => >); onkeypress = (event) => >;
Event type
Event properties
This interface also inherits properties of its parents, UIEvent and Event . KeyboardEvent.altKey Read only Returns a boolean value that is true if the Alt ( Option or β₯ on macOS) key was active when the key event was generated. KeyboardEvent.code Read only Returns a string with the code value of the physical key represented by the event.
Warning: This ignores the user’s keyboard layout, so that if the user presses the key at the «Y» position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return «KeyY», even if the user has a QWERTZ keyboard (which would mean the user expects a «Z» and all the other properties would indicate a «Z») or a Dvorak keyboard layout (where the user would expect an «F»). If you want to display the correct keystrokes to the user, you can use Keyboard.getLayoutMap() .
KeyboardEvent.ctrlKey Read only Returns a boolean value that is true if the Ctrl key was active when the key event was generated. KeyboardEvent.isComposing Read only Returns a boolean value that is true if the event is fired between after compositionstart and before compositionend . KeyboardEvent.key Read only Returns a string representing the key value of the key represented by the event. KeyboardEvent.locale Read only Returns a string representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn’t know the keyboard’s locale.
Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.
KeyboardEvent.location Read only Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations. KeyboardEvent.metaKey Read only Returns a boolean value that is true if the Meta key (on Mac keyboards, the β Command key; on Windows keyboards, the Windows key ( β )) was active when the key event was generated. KeyboardEvent.repeat Read only Returns a boolean value that is true if the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKey Read only Returns a boolean value that is true if the Shift key was active when the key event was generated.
Examples
addEventListener keypress example
div> label for="sample">Focus the input and type something:label> input type="text" name="text" id="sample" /> div> p id="log">p>
const log = document.getElementById("log"); const input = document.querySelector("input"); input.addEventListener("keypress", logKey); function logKey(e) log.textContent += ` $e.code>`; >
onkeypress equivalent
How to detect when the user stops typing
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
- Implement an auto-save feature
- Keep your local data store up-to-date
- 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');
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);
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); >
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. '; >
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!
How to detect when the user stops typing in JavaScript
It is pretty common to listen for keystroke events ( keypress , keyup , and keydown ) to input elements to perform different tasks. But sometimes, you want to know when the user stops entering text in an input field.
Let us say that you have got the following HTML search form on your website:
form> input type="search" id="input-text" placeholder="Start typing. "> form>
We want to add a live search to this form and display search results while the user types. 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.currentTarget.value; // TODO: Make HTTP Request Here >);
The above solution should work fine, but it is not an optimal way of solving this problem. You’ll end up sending dozens of concurrent requests to the server as the user keeps typing.
With a few modifications, we can easily make the above code more practical and more performant.
The idea is to keep track of the user’s input and only make an HTTP request when the user has stopped typing:
let timer; // Timer identifier const waitTime = 500; // Wait time in milliseconds // Search function const search = (text) => // TODO: Make HTTP Request HERE >; // Listen for `keyup` event const input = document.querySelector('#input-text'); input.addEventListener('keyup', (e) => const text = e.currentTarget.value; // Clear timer clearTimeout(timer); // Wait for X ms and then process the request timer = setTimeout(() => search(text); >, waitTime); >);
βοΈ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.