Episode 1 — Fundamentals / 1.15 — Event Handling in JavaScript

1.15.d — Working with Classes (classList) & Events

In one sentence: classList is how you toggle visual state in response to events — add, remove, and toggle CSS classes instead of rewriting big style strings 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

MethodEffect
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

  1. classList keeps JS focused on state, CSS on presentation.
  2. toggle(token, bool) avoids manual if (contains) branches.
  3. Pair click (and keyboard) handlers with meaningful class names.

Explain-It Challenge

Explain without notes:

  1. Why prefer classList.add("open") over el.style.display = "block" for a menu?
  2. What does el.classList.toggle("active", false) do?
  3. How does contains help before calling add if you want idempotent “ensure on” behavior?

Navigation: ← 1.15.c — Forms · 1.15.e — Browser & Window Events →