Script Valley
JavaScript in the Browser: DOM, Events & APIs
Events and Event HandlingLesson 2.5

Keyboard and input events: keydown, keyup, and input

keydown event, keyup event, input event, e.key, e.code, e.repeat, compositionstart, debouncing input

Keyboard and Input Events

Three events cover keyboard and text input:

keydown fires the moment a key is pressed. keyup fires on release. input fires every time the value of an <input> or <textarea> changes — including paste, autocomplete, and speech input.

const field = document.querySelector('#search');

field.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') submitSearch();
  if (e.key === 'Escape') field.blur();
});

// Live counter — fires on every character
field.addEventListener('input', (e) => {
  counter.textContent = e.target.value.length;
});

e.key vs e.code

e.key gives the printed character or action name ('a', 'Enter', 'ArrowUp'). e.code gives the physical key ('KeyA', 'Enter') — useful for games where layout independence matters.

Debouncing input

For expensive operations like search API calls, debounce to avoid firing on every keystroke.

let timer;
field.addEventListener('input', (e) => {
  clearTimeout(timer);
  timer = setTimeout(() => fetchResults(e.target.value), 300);
});