Episode 1 — Fundamentals / 1.15 — Event Handling in JavaScript

1.15.b — Mouse, Keyboard, Scroll Events & Strict Mode

In one sentence: Mouse and keyboard events power most UIs; scroll events fire often and need care; 'use strict' tightens the language so common mistakes become errors instead of silent bugs.

Navigation: ← 1.15.a — addEventListener & Bubbling · 1.15.c — Forms & preventDefault →


1. Mouse events (common)

EventWhen it fires
clickPress + release on same element (primary button by default)
dblclickDouble click
mousedown / mouseupButton pressed / released
mousemovePointer moves over the element (fires very often)
mouseenter / mouseleaveEnter/leave element — do not bubble
mouseover / mouseoutSimilar but bubble
contextmenuRight-click (or context key) — often paired with preventDefault for custom menus

Coordinates: clientX / clientY (viewport), pageX / pageY, offsetX / offsetY — pick the space you need.


2. Keyboard events

EventTypical use
keydownFirst fire when key goes down; repeats while held
keyupWhen key released
keypressDeprecated — avoid

Which key: Prefer event.key (“Enter”, “a”, “Escape”) for readable logic. event.code describes physical key (“KeyQ”) — better for games / layouts independent of character. Legacy keyCode — avoid.

Modifiers: event.shiftKey, ctrlKey, altKey, metaKey (Cmd on Mac).


3. Scroll events

  • element.addEventListener("scroll", …) — fires when that element’s scroll position changes (overflow scroll).
  • window.addEventListener("scroll", …) — document / viewport scrolling.

Performance: Scroll handlers can run dozens of times per second. Patterns: throttle / debounce, requestAnimationFrame, avoid heavy layout reads/writes in the handler. passive: true (see 1.15.e) when you will not call preventDefault on scroll/touch.


4. Strict mode: 'use strict'

Place at the top of a file or top of a function:

"use strict";

function demo() {
  undeclaredVar = 1; // ReferenceError in strict mode
}
Without strictWith strict
Assigning to undeclared variable may create globalReferenceError
this in sloppy “plain” function calls can be windowthis is undefined in non-method calls (ES modules are strict by default)

ES modules (<script type="module">) are strict automatically. Use strict mode in scripts to catch mistakes early.


5. Key takeaways

  1. click is the workhorse; mousedown/mouseup for drag-like interactions.
  2. Use event.key for shortcuts and form UX.
  3. Scroll listeners need performance discipline; strict mode catches accidental globals.

Explain-It Challenge

Explain without notes:

  1. Why can mousemove handlers hurt performance if they do a lot of work?
  2. Why prefer event.key over keyCode?
  3. What problem does 'use strict' solve with undeclared variables?

Navigation: ← 1.15.a — addEventListener & Bubbling · 1.15.c — Forms & preventDefault →