Episode 1 — Fundamentals / 1.15 — Event Handling in JavaScript
1.15.d — Working with Classes (classList) & Events
In one sentence:
classListis how you toggle visual state in response to events — add, remove, and toggle CSS classes instead of rewriting bigstylestrings in JavaScript.
Navigation: ← 1.15.c — Forms · 1.15.e — Browser & Window Events →
1. Why classes + events?
CSS should own what things look like; JS should own what state the UI is in. Events change state; classes select which CSS rules apply.
menuButton.addEventListener("click", () => {
nav.classList.toggle("nav--open");
});
.nav--open { transform: translateX(0); }
2. classList methods
| Method | Effect |
|---|---|
add("a", "b") | Adds one or more tokens if missing |
remove("a", "b") | Removes tokens if present |
toggle("active") | Adds if absent, removes if present |
toggle("active", force) | If force is true, add; if false, remove |
contains("active") | Returns true / false |
replace("old", "new") | Swap one token for another |
tokenList is live — reflects the class attribute immediately.
3. Example: open/close panel
const panel = document.querySelector("#panel");
const openBtn = document.querySelector("#open");
const closeBtn = document.querySelector("#close");
openBtn.addEventListener("click", () => {
panel.classList.add("is-visible");
});
closeBtn.addEventListener("click", () => {
panel.classList.remove("is-visible");
});
Use BEM-like state classes (is-visible, has-error) or data attributes for clarity (see 1.10.a).
4. aria-* and keyboard (preview)
Toggling visibility with classes should often sync aria-expanded for accessibility — connect to 1.5.e. Also handle keydown (Escape) to close — full pattern in later modules.
5. Key takeaways
classListkeeps JS focused on state, CSS on presentation.toggle(token, bool)avoids manualif (contains)branches.- Pair click (and keyboard) handlers with meaningful class names.
Explain-It Challenge
Explain without notes:
- Why prefer
classList.add("open")overel.style.display = "block"for a menu? - What does
el.classList.toggle("active", false)do? - How does
containshelp before callingaddif you want idempotent “ensure on” behavior?
Navigation: ← 1.15.c — Forms · 1.15.e — Browser & Window Events →