JavaScript Events - Exercise 2

By default, an event moves from the target element up through its ancestors. This is called bubbling.

parent.addEventListener('click', () => console.log('parent'));
child.addEventListener('click', () => console.log('child'));
// Clicking child logs child, then parent

Call stopPropagation() on the event when the child should not notify its ancestors.

child.addEventListener('click', (event) => {
  event.stopPropagation();
});

Use event delegation: listen on the stable parent and find the clicked item with closest().

list.addEventListener('click', (event) => {
  const item = event.target.closest('li');
  if (item) item.classList.toggle('selected');
});

event.target is where the event started; event.currentTarget is the element whose listener is running.

list.addEventListener('click', (event) => {
  console.log(event.target);
  console.log(event.currentTarget);
});

Use preventDefault() inside the link handler to cancel its browser default action.

link.addEventListener('click', (event) => {
  event.preventDefault();
  showPreview();
});

Pass an options object with once: true. The browser removes the listener after its first invocation.

button.addEventListener('click', showWelcome, { once: true });

Set capture: true to run the listener while the event travels down to its target.

parent.addEventListener('click', handleClick, { capture: true });

Delegate from the list, guard against non-checkbox targets, then use checked to update state.

settings.addEventListener('change', (event) => {
  if (event.target.matches('input[type="checkbox"]')) {
    saveSetting(event.target.name, event.target.checked);
  }
});