DevPath
Mid lesson · 12 min

Understand events, delegation and equality

Predict callback order and avoid fragile DOM handlers.

Read the event loop

Synchronous code runs first. Promise callbacks enter the microtask queue; timer callbacks run in later tasks. Do not rely on a timer with zero delay to run before a resolved promise. Trace a short program on paper, then verify the printed order in a browser console.

Delegate repeated controls

For a changing list, one listener on a stable parent can handle clicks from many children. Use closest to find the intended control and verify that it belongs to the container. A click may originate from an icon inside a button, so comparing only event.target to the button misses it.

list.addEventListener('click', (event) => {
  const button = event.target.closest('button[data-id]');
  if (!button || !list.contains(button)) return;
  openItem(button.dataset.id);
});

Make comparisons intentional

Loose equality can coerce an empty string, zero, and false into surprising matches. Prefer strict equality and normalize values once at input boundaries. If a URL parameter is an ID, parse and validate it before comparison. Add tests for both numeric-looking strings and actual numbers.

Check your understanding

Why can `event.target.dataset.id` fail when clicking an icon inside a button?

Show explanation

The target is the icon, not the button. Find the nearest matching button and verify it is inside the list.

You can read for free. Create an account to save your progress.

Next lesson: Make forms understandable to everyone →

Put this lesson into practice

A practice activity at this level in the same module.

Try: Make a custom list keyboard accessible

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.