CodeBlanks Logo Icon CodeBlanks

Summary - Event handling

JavaScript course · Intermediate · Lesson 42/134

Manage many buttons with a single listener using event delegation and preventDefault.

Summary - Event handling

In this group you learned how events propagate and how to control them. Bubbling means the event goes from child to parent; you stop it with stopPropagation. With event delegation a single listener manages many children.

list.addEventListener('click', (event) => {
  const link = event.target.closest('a');
  if (link) event.preventDefault();
});

preventDefault blocks the default behavior, while once: true limits the listener to a single run.

Exercise Prevent link clicks with delegation

Define a list variable and select the #list element. Add a single click listener. Find the clicked link with event.target.closest('a') and prevent the default navigation with event.preventDefault().

Show example solution
const list = document.querySelector('#list');
list.addEventListener('click', (event) => {
  const link = event.target.closest('a');
  if (link) {
    event.preventDefault();
    console.log('link clicked');
  }
});

Exercise Add a once: true listener for button

Define a button variable and select the #button element. Add a click listener and pass { once: true } as the third parameter.

Show example solution
const button = document.querySelector('#button');
button.addEventListener('click', () => {
  console.log('clicked');
}, { once: true });

Test yourself

  1. Match concepts to their effects

    stopPropagation
    Stops propagation
    preventDefault
    Default prevented
    event.target.closest
    Finds ancestor
    once: true
    Runs only once
  2. Find the ancestor in delegation

    list.addEventListener('click', (event) => {
      const link = event.target.____('a');
      if (link) { event.preventDefault(); }
    });
    Show answer
    list.addEventListener('click', (event) => {
      const link = event.target.closest('a');
      if (link) { event.preventDefault(); }
    });

All lessons in Intermediate