JavaScript keydown and keyup Events
Learn JavaScript keyboard events: how keydown and keyup differ, the KeyboardEvent object (key vs code, modifier flags, repeat).
Introduction to Keyboard Events in JavaScript
JavaScript keyboard events let your page react the moment a user presses or releases a key. They are the foundation of search-as-you-type inputs, keyboard shortcuts, game controls, and accessible navigation. This chapter focuses on the two events you will reach for most often — keydown and keyup — explains how they differ, walks through the KeyboardEvent object that each handler receives, and finishes with practical, runnable examples.
If you are new to handling events in general, start with Introduction to Browser Events and Event Handling in the DOM first.
keydown vs. keyup at a Glance
Both events fire on the element that currently has focus (or on document if nothing specific is focused). The difference is when in the key's lifecycle they fire:
| Event | Fires when… | Repeats while held? | Typical use |
|---|---|---|---|
keydown | A key is pressed down | Yes — repeatedly | Shortcuts, game movement, preventing input |
keyup | A key is released | No — once per press | Detecting when a press ends, finalizing UI |
A single tap of a key produces one keydown then one keyup. Holding a key down fires keydown over and over (you can detect these auto-repeats with event.repeat), but keyup only fires once, when you finally let go.
The legacy
keypressevent is deprecated and should not be used in new code. To react to the text a user types, listen for theinputevent instead.
Understanding keydown and keyup
The keydown Event
The keydown event occurs when a user presses a key on the keyboard. It fires before the character is inserted into a field, which is exactly why it is the right place to call event.preventDefault() when you want to block input. This event is useful whenever the timing of the press matters — gaming, accessibility features, or interactive controls.
Example of keydown Event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example of Keydown Event</title>
<style>
.highlight { background-color: yellow; }
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
const inputField = document.getElementById('inputField');
inputField.addEventListener('keydown', function(event) {
console.log('Key down:', event.key);
if (event.key === "Enter") {
this.classList.add('highlight');
event.preventDefault(); // Prevents the default action of the enter key
}
});
});
</script>
</head>
<body>
<input type="text" id="inputField" placeholder="Press 'Enter' to highlight" />
</body>
</html>The code listens for a keydown event on the input field and checks if the pressed key is "Enter". If so, it changes the background color of the input field to yellow (highlight class) and prevents the default form submission or other actions typically associated with the Enter key.
The keyup Event
The keyup event triggers when a key is released, after the keydown event (note: the legacy keypress event is deprecated and rarely used in modern web development). This event is suited for cases where you need to know when a key press is concluded, such as when updating a user interface or controlling multimedia content.
Example of keyup Event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example of Keyup Event</title>
<style>
.normal { background-color: transparent; }
.active { background-color: lightgreen; }
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
const textArea = document.getElementById('textArea');
textArea.addEventListener('keyup', function(event) {
console.log('Key up:', event.key);
if (event.key === "Control") {
this.classList.remove('active');
this.classList.add('normal');
}
});
textArea.addEventListener('keydown', function(event) {
if (event.key === "Control") {
this.classList.add('active');
}
});
});
</script>
</head>
<body>
<textarea id="textArea" rows="4" cols="50" placeholder="Press and release 'Control' to see the effect"></textarea>
</body>
</html>This code makes the textarea change its background color to light green (active class) when the Control key is pressed and returns it to transparent (normal class) when the Control key is released.
The KeyboardEvent Object
Every keydown and keyup handler receives a KeyboardEvent. Knowing its key properties is what lets you write reliable keyboard logic.
key vs. code
These two properties are easy to confuse, and choosing the wrong one is the most common source of keyboard bugs:
event.key— the character or named value produced, respecting the keyboard layout and modifiers. Pressing theAkey gives"a", or"A"with Shift held. Naming keys:"Enter","Escape","ArrowLeft"," "(space).event.code— the physical key on the keyboard, independent of layout or modifiers. The same physical key is always"KeyA"whether the user typesa,A, or has a non-QWERTY layout.
Use key when you care about the character (text input, shortcuts spelled out for the user). Use code when you care about position — for example WASD game controls that should work regardless of layout.
document.addEventListener('keydown', function (event) {
console.log(event.key, event.code);
});
// Pressing Shift+A on QWERTY logs: "A" "KeyA"
// Pressing the space bar logs: " " "Space"Modifier keys and repeat
The event also reports which modifier keys are held and whether the press is an OS auto-repeat:
event.altKey,event.ctrlKey,event.shiftKey,event.metaKey— booleans,truewhile that modifier is held. (metaKeyis Cmd on macOS, the Windows key elsewhere.)event.repeat—truewhen a held-down key fireskeydownagain automatically. Check it to ignore auto-repeats.
document.addEventListener('keydown', function (event) {
// Cross-platform "save" shortcut, ignoring auto-repeat.
if ((event.ctrlKey || event.metaKey) && event.key === 's' && !event.repeat) {
event.preventDefault();
console.log('Save triggered');
}
});Reading the modifier flags directly (as above) is more robust than tracking a separate ctrlPressed variable, because the flags are guaranteed to be in sync with reality even if you miss a keyup.
Advanced Uses of Keyboard Events in JavaScript
Using the power of keyboard events like keydown and keyup can transform ordinary web applications into highly interactive, accessible, and efficient platforms. Here, we expand on their uses by incorporating them into more complex scenarios such as custom hotkeys, game controls, and accessibility features.
Implementing Custom Hotkeys
Custom hotkeys allow users to perform actions quickly, enhancing productivity and user experience. This example demonstrates how to create a simple custom hotkey (Ctrl + S) to simulate a save action, which could be adapted to trigger specific functionalities in real applications.
Example of Custom Hotkeys
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Custom Hotkeys Example</title>
<script>
document.addEventListener('DOMContentLoaded', function () {
let ctrlPressed = false;
document.addEventListener('keydown', function(event) {
if (event.key === "Control") {
ctrlPressed = true;
}
// Use toLowerCase() for case-insensitive matching
if (event.key.toLowerCase() === "s" && ctrlPressed) {
alert('Saving your progress!');
event.preventDefault(); // Prevent default to stop other actions like browser shortcuts
}
});
document.addEventListener('keyup', function(event) {
if (event.key === "Control") {
ctrlPressed = false;
}
});
});
</script>
</head>
<body>
<p>Press <strong>Ctrl + S</strong> to simulate a save action.</p>
</body>
</html>Handling Game Controls
Game controls are crucial for browser-based games. This example provides a simple implementation of arrow key controls to move a player object within a game area, offering a basic framework that can be expanded into more complex gaming mechanics.
Example of Game Controls
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Game Control Example</title>
<style>
#gameArea {
width: 300px;
height: 300px;
border: 1px solid black;
position: relative;
}
#player {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 125px;
left: 125px;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
const player = document.getElementById('player');
// Note: offsetLeft/Top don't account for container padding or scroll offsets.
// For production, consider using getBoundingClientRect() or adding padding offsets.
let posX = player.offsetLeft;
let posY = player.offsetTop;
document.addEventListener('keydown', function(event) {
switch (event.key) {
case "ArrowUp":
posY -= 10;
break;
case "ArrowDown":
posY += 10;
break;
case "ArrowLeft":
posX -= 10;
break;
case "ArrowRight":
posX += 10;
break;
}
player.style.left = posX + 'px';
player.style.top = posY + 'px';
});
});
</script>
</head>
<body>
<div id="gameArea">
<div id="player"></div>
</div>
<p>Use arrow keys to move the red square within the game area.</p>
</body>
</html>Enhancing Accessibility
Accessibility enhancements help make web applications usable by people with disabilities. This example focuses on using keydown events to navigate through links using the keyboard’s arrow keys, facilitating keyboard-driven navigation for users who cannot use a mouse.
Example of Accessibility Enhancement
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Accessibility Navigation Example</title>
<script>
document.addEventListener('DOMContentLoaded', function () {
const links = document.querySelectorAll('a');
let currentFocus = 0;
links[currentFocus].focus();
document.addEventListener('keydown', function(event) {
if (event.key === "ArrowDown") {
currentFocus = (currentFocus + 1) % links.length;
links[currentFocus].focus();
event.preventDefault();
}
if (event.key === "ArrowUp") {
currentFocus = (currentFocus - 1 + links.length) % links.length;
links[currentFocus].focus();
event.preventDefault();
}
});
});
</script>
</head>
<body>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
<p>Use the Up and Down arrow keys to navigate between the links.</p>
</body>
</html>These examples not only illustrate the technical implementation of keydown and keyup events but also demonstrate their practical applications in enhancing the interactivity and accessibility of web applications. By incorporating these advanced functionalities, developers can create more engaging and inclusive user experiences.
Conclusion
Keyboard events like keydown and keyup are indispensable for creating dynamic and interactive web applications. Remember the essentials: keydown fires (and repeats) on press, keyup fires once on release, event.key gives you the character while event.code gives you the physical key, and the modifier flags plus event.repeat let you build robust shortcuts. The examples above are a starting point for adding keyboard interaction to your own projects.
Related Chapters
- Introduction to Browser Events — how events work at a high level.
- Event Handling in the DOM —
addEventListener, handlers, and removal. - Events: change, input, cut, copy, paste — react to the text that actually lands in a field.
- Focusing: focus and blur — pairs naturally with keyboard navigation.
- Bubbling and Capturing — how keyboard events propagate through the DOM.