Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C2 · Lekcja 9
ZadanieHTML: <p id='out'>press Escape</p>. JS: listen on document for keydown; when event.key === 'Escape', set #out textContent to 'escape pressed' and log 'escape'.

Zdarzenia klawiatury: naciśnięcie klawisza, modyfikatory i klawisz Escape

100 XP8 min
Teoria

Three keyboard events

document.addEventListener("keydown",  (e) => { /* key was pressed */ });
document.addEventListener("keypress", (e) => { /* deprecated — don't use */ });
document.addEventListener("keyup",    (e) => { /* key was released */ });

keydown is what you want 95% of the time. It fires once when the key goes down (and repeatedly while held). keypress is deprecated. keyup is only for "did they release this combo before doing X."

event.key vs event.code

e.key   === "Escape"     // what character/name the user got
e.code  === "Escape"     // which physical key, regardless of layout
e.key   === "ArrowUp"
e.key   === "Enter"

Use event.key for "did they press Escape?" — works across keyboard layouts. Use event.code for "did they press the key where WASD is on QWERTY?" — game-style shortcuts that should survive layout swaps.

Modifier keys

if (e.metaKey  && e.key === "k") { /* Cmd+K on Mac */ }
if (e.ctrlKey  && e.key === "k") { /* Ctrl+K elsewhere */ }
if (e.shiftKey && e.key === "Enter") { /* Shift+Enter */ }

e.altKey, e.shiftKey, e.ctrlKey, e.metaKey are booleans on the event. Combine with e.key for shortcuts.

The Escape-to-close pattern

document.addEventListener("keydown", (e) => {
  if (e.key === "Escape") dialog.classList.remove("open");
});

Single source of truth for "what does Escape do." Don't sprinkle Escape handlers across components — one place at the document level wins.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.