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)
| Event | When it fires |
|---|---|
click | Press + release on same element (primary button by default) |
dblclick | Double click |
mousedown / mouseup | Button pressed / released |
mousemove | Pointer moves over the element (fires very often) |
mouseenter / mouseleave | Enter/leave element — do not bubble |
mouseover / mouseout | Similar but bubble |
contextmenu | Right-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
| Event | Typical use |
|---|---|
keydown | First fire when key goes down; repeats while held |
keyup | When key released |
keypress | Deprecated — 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 strict | With strict |
|---|---|
| Assigning to undeclared variable may create global | ReferenceError |
this in sloppy “plain” function calls can be window | this 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
clickis the workhorse;mousedown/mouseupfor drag-like interactions.- Use
event.keyfor shortcuts and form UX. - Scroll listeners need performance discipline; strict mode catches accidental globals.
Explain-It Challenge
Explain without notes:
- Why can
mousemovehandlers hurt performance if they do a lot of work? - Why prefer
event.keyoverkeyCode? - What problem does
'use strict'solve with undeclared variables?
Navigation: ← 1.15.a — addEventListener & Bubbling · 1.15.c — Forms & preventDefault →