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)

  1. Skim before labs or interviews.
  2. Gaps — README.md → 1.15.a…1.15.e.
  3. Drills — 1.15-Exercise-Questions.md.
  4. 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)
PropertyMeaning
targetDeepest element that triggered event
currentTargetElement that owns this listener
stopPropagation()Stop further propagation
preventDefault()Cancel default browser action

Forms

TaskPattern
Read fieldform.elements.name.value or FormData
Block reloadsubmit → preventDefault()
Built-in UI validationcheckValidity() / reportValidity()
Every keystrokeinput
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

EventFires
DOMContentLoadedHTML parsed → DOM ready
load (window)Page + key resources loaded
resizeViewport size changed — throttle
scrollScroll position changed — often { passive: true }

Strict mode

"use strict";   // file or function top
  • Undeclared assignment → ReferenceError
  • Modules = strict by default

Master workflow

  1. Pick event (click, submit, input, …).
  2. Attach with addEventListener (named fn if you need removal).
  3. Use target / currentTarget correctly (delegation).
  4. preventDefault when blocking defaults; stopPropagation only when needed.
  5. Forms: preventDefault + FormData + fetch pattern.
  6. UI state: classList, not giant style strings.
  7. DOMContentLoaded to boot; load for asset-dependent init; throttle resize/scroll.

End of 1.15 quick revision.