Events and Event Delegation

Respond to clicks, keys, input and more; understand bubbling, capturing, default actions and delegation.

Beginner · about 5 hours · difficulty 2/5

Learn first: DOM Manipulation

Events are how the browser tells your code that something happened: a click, a key press, a form submit, a resize, a network response. Handling them well is the core of interactivity.

Listening

element.addEventListener("click", handler) attaches a listener; removeEventListener needs the same function reference to detach it. The handler receives an event object with details such as target, currentTarget, key and clientX.

Propagation

Events travel in three phases: capture (from window down), target, then bubble (back up). Most listeners run in the bubble phase.

  • event.target is where the event started; event.currentTarget is the element whose listener is running.
  • stopPropagation() stops the journey (use rarely, it breaks other code's assumptions).
  • preventDefault() cancels the default action: following a link, submitting a form, scrolling.

Delegation

Instead of 500 listeners on 500 list items, attach one to the parent and check event.target.closest("li"). It uses less memory and automatically covers items added later. React uses a form of this internally.

Choosing the right events

  • input fires on every change, change on commit.
  • Use submit on forms, not click on the button, so Enter works.
  • pointer events unify mouse, touch and pen.
  • keydown for shortcuts; check event.key (not deprecated keyCode).
  • Mark scroll and touch listeners { passive: true } for smoother scrolling, and use { once: true } or an AbortController signal to clean up.

Move on when you can build a keyboard-accessible dropdown menu that closes on outside click and Escape, using delegation for its items.

Key concepts

  • addEventListener and removal
  • The event object
  • Bubbling and capturing
  • target vs currentTarget
  • preventDefault and stopPropagation
  • Event delegation
  • Pointer and keyboard events
  • passive, once and AbortController signals
  • Custom events

Mini project

Build a kanban board in vanilla JS with delegated click handlers for cards, keyboard shortcuts for moving cards between columns, and an outside-click close for the card menu.

Check yourself

Why does event delegation keep working for list items added after the listener was attached?

Free resources