Flash cards
Review the key moves
What is the main idea behind JavaScript Keyboard Events?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
<input id="k" type="text" placeholder="Press a key"> <p id="demo"></p> <script> ___ k = document.getElementById("k");Put the learning moves in the order that makes the concept easiest to apply.
Keyboard Events happen when the user presses a key on the keyboard:
- keydown (key is pressed down)
- keyup (key is released)
- keypress (deprecated)
keypress only fires for character keys (a or 5), not for control keys (alt or backspace).
Developers are advised to use keydown or keyup instead.
Using event.key
Example
<input id="k" type="text" placeholder="Press a key"> <p id="demo"></p> <script> const k = document.getElementById("k");
// Let k listen for keydown k.addEventListener("keydown", function (event) { // Then display the event.key document.getElementById("demo").innerHTML = "You pressed: " + event.key;
});
</script>Key Properties
The KeyboardEvent object provides useful properties to determine which key was involved in the event:
| Property | Description | When pressing Z |
|---|---|---|
| event.key | Returns the value of the key. Can vary based on language settings. | Returns z (or Z if shift is held) |
| event.code | Returns the key code. Constant, regardless of language settings. | Always returns "KeyZ" |
You can also detect modifier keys using properties like event.ctrlKey, event.shiftKey, event.altKey, and event.metaKey to implement key combinations (e.g., Ctrl + S).
Using event.code
Runnable example
<input id="in01" type="text" placeholder="Press Enter"> <p id="demo"></p> <script> const in01 = document.getElementById("in01");
// Let in01 listen for keydown in01.addEventListener("keydown", function (event) { // If event.code was "enter", then display text
if (event.code === "Enter") {
document.getElementById("demo").innerHTML = "Enter was pressed!";
}
});
</script>Summary
JavaScript provides keyboard events to detect and handle user input from the keyboard, enabling interactive web experiences like form validation, game controls, and keyboard shortcuts.