Episode 1 — Fundamentals / 1.15 — Event Handling in JavaScript
1.15 — Event Handling: Quick Revision
Compact cheat sheet. Print-friendly.
How to use this material (instructions)
- Skim before labs or interviews.
- Gaps —
README.md→1.15.a…1.15.e. - Drills —
1.15-Exercise-Questions.md. - Polish —
1.15-Interview-Questions.md.
addEventListener
el.addEventListener("click", handler, { capture, once, passive });
el.removeEventListener("click", handler, { capture: sameAsAdd });
- Same function reference required to remove.
- Capture:
{ capture: true }— run on way down the tree.
Flow & properties
Capture: window → … → target
Bubble: target → … → window (default listener phase)
| Property | Meaning |
|---|---|
target | Deepest element that triggered event |
currentTarget | Element that owns this listener |
stopPropagation() | Stop further propagation |
preventDefault() | Cancel default browser action |
Forms
| Task | Pattern |
|---|---|
| Read field | form.elements.name.value or FormData |
| Block reload | submit → preventDefault() |
| Built-in UI validation | checkValidity() / reportValidity() |
| Every keystroke | input |
| Committed value (text) | change (usually on blur) |
Prefer addEventListener over onsubmit / onchange attributes for new code.
classList (with events)
el.classList.add("a", "b");
el.classList.remove("a");
el.classList.toggle("open");
el.classList.toggle("open", bool);
el.classList.contains("open");
el.classList.replace("was", "now");
Document / window lifecycle
| Event | Fires |
|---|---|
DOMContentLoaded | HTML parsed → DOM ready |
load (window) | Page + key resources loaded |
resize | Viewport size changed — throttle |
scroll | Scroll position changed — often { passive: true } |
Strict mode
"use strict"; // file or function top
- Undeclared assignment → ReferenceError
- Modules = strict by default
Master workflow
- Pick event (
click,submit,input, …). - Attach with
addEventListener(named fn if you need removal). - Use
target/currentTargetcorrectly (delegation). preventDefaultwhen blocking defaults;stopPropagationonly when needed.- Forms:
preventDefault+ FormData + fetch pattern. - UI state:
classList, not giantstylestrings. DOMContentLoadedto boot;loadfor asset-dependent init; throttleresize/scroll.
End of 1.15 quick revision.