Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

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.

Esc
F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
F11
F12
Q
W
E
R
T
Y
U
I
O
P
A
S
D
F
G
H
J
K
L
Z
X
C
V
B
N
M
Ctrl
Alt
SPACE
Alt
Ctrl

Keyboard interaction generates events that JavaScript can detect and handle.

Keyboard Event Flow

How a Keyboard Event Works
User Presses a Key
→
keydown Key is Pressed
→
JavaScript Event Handler
→
Output Action / Message

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);
Event Type: keydown
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.");
}
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.");
}
Up arrow 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.