HOWTO · JavaScript
How to Detect Keyboard Input Event in JavaScript
Learn how to detect keyboard input events in JavaScript with our comprehensive guide. Explore various methods such as keydown, keyup, and keypress, complete with code examples and detailed explanations. Enhance your web applications by mastering keyboard input detection and create interactive user experiences.
On this page
Keyboard input in a web page is handled with keyboard events. Register a listener with addEventListener(), then read the event object passed to its callback. Use keydown to respond as a key is pressed and keyup to respond after it is released.
Listen for Keyboard Events with addEventListener()
Attach the listener to the element that should receive input. Use document when the page should respond while focus is anywhere on the page, or attach it to a form control when the behavior belongs to that control. The callback receives a KeyboardEvent as its parameter, so name that parameter and read its properties instead of relying on a global event value.
This runnable illustration uses a small stand-in for document and supplies one key event, so its listener shape can be tried in a JavaScript runtime. In a browser, use the real document to receive keyboard input.
const listeners = new Map();
const document = {
addEventListener(type, callback) {
listeners.set(type, callback);
}
};
document.addEventListener("keydown", (event) => {
console.log(`Key pressed: ${event.key}`);
});
listeners.get("keydown")({ key: "ArrowDown" });
A real browser calls the callback when the user presses a key. The stand-in above invokes it with an object containing the same key value used by the handler; it does not simulate browser input or other KeyboardEvent behavior.
Choose Between keydown and keyup
A keydown event fires when a key is pressed. It is a good fit for actions that should begin immediately, such as moving a game character while a key is held. A keyup event fires when the key is released, which suits actions that should happen once the user finishes holding a key. Choose the event based on when the action should occur. A held key may produce repeated keydown events, so account for that when an action should happen only once.
Read KeyboardEvent.key and Handle Special Keys
Use event.key to identify the key in a handler. It returns readable values such as "a", "Enter", and "ArrowDown", which makes comparisons straightforward. For example, an arrow-key handler can check whether event.key === "ArrowDown" before moving an item down. Modifier state is available on the event too, through properties such as event.shiftKey and event.ctrlKey.
The value of event.key reflects the key’s meaning under the active keyboard layout and modifiers. Use event.code when behavior should follow a physical key position, such as a game control that stays in the same place across layouts. For ordinary commands and named keys, event.key is usually the clearer choice.
Prevent a Key’s Default Action When Needed
A keyboard event handler can call event.preventDefault() to suppress a browser action associated with that key, such as scrolling when an arrow key is used for a custom interface. Call it only when the page is taking responsibility for that action, and check event.cancelable when the behavior depends on cancellation. It does not stop the event from reaching other listeners; use propagation methods only when that is also the intended behavior. Ordinary key detection needs no cancellation.
Why keypress Should Usually Be Avoided
Avoid using keypress for new keyboard handling. It is deprecated, and it does not cover the full range of keys consistently. Use keydown or keyup to observe keyboard actions and event.key to read the key value. Do not depend on event.char or the legacy keyCode property for current code; use the standard event properties that describe the key and its state.