Keyboard Events
Learn how JavaScript detects keyboard interactions such as pressing and releasing keyboard keys.
What are Keyboard Events?
Keyboard events are generated when a user interacts with the keyboard.
JavaScript provides events such as keydown and keyup to detect keyboard interactions.
Simple Definition
A keyboard event occurs when the user presses or releases a keyboard key.
JavaScript can detect the event and execute specific code.
Keyboard interaction generates events that JavaScript can detect and handle.
Keyboard Event Flow
Common Keyboard Events
keydown
Occurs when a keyboard key is pressed down.
keyup
Occurs when a keyboard key is released.
key
The key property identifies the actual key value, such as A or Enter.
Example 1: Keyboard Event Information
A keyboard event contains useful information such as the event type, key value, and key code.
const event = {
type: "keydown",
key: "A",
code: "KeyA"
};
console.log("Event Type:", event.type);
console.log("Key:", event.key);
console.log("Code:", event.code);
Key: A
Code: KeyA
Example 2: Checking a Pressed Key
We can check the value of a key and perform an action based on that key.
const key = "Enter";
if (key === "Enter") {
console.log("Enter key was pressed.");
}
Example 3: Detecting Different Keys
JavaScript can check different key values and execute different instructions.
const key = "ArrowUp";
if (key === "ArrowUp") {
console.log("Up arrow was pressed.");
}
else {
console.log("Another key was pressed.");
}
Important Note
The CIIT JavaScript compiler is designed for console-based JavaScript execution.
Therefore, the Try It examples above use normal JavaScript objects and conditions to demonstrate keyboard-event information without depending on browser-only objects such as document.
Summary
Keyboard events allow JavaScript to respond to keyboard interactions. The most commonly used events are keydown and keyup. Keyboard-event information can include the key and code values, which can be used to perform specific actions in a web application.