Event delegation~ Browser APIs ~

Event delegation

I find it very interesting how we start forgetting stuff when technology evolves. One of these things is the event delegation. Today, when we pretty much always use a framework, the event bubbling and capturing is not a thing anymore. The tools that we rely on are handling those processes. I remember how this was one of the common questions at interviews for front-end developer positions. And so, I decided to dedicate a chapter to it.

Consider the following example:

<div id="container">
  <header>Hello</header>
  <button id="button">call to action</button>
</div>

document
  .querySelector("#button")
  .addEventListener("click", () => {
  // ...
});

When the page loads initially, we attach a listener to the <button> element. It works well unless we touch the DOM. As soon as we replace the container's content, we have to re-attach the listener. It may seem a silly problem now, but it was a big thing a couple of years ago.

If we write vanilla JavaScript and have to manipulate the DOM elements, we should ensure our listeners are present. One of the solutions for this is to attach the listener to a parent element that doesn't change. In our case this is <div id="container">. Then we rely on the event.target to determine where the event comes from.

document
  .querySelector("#container")
  .addEventListener('click', (event) => {
  // event.target....
});

This works because of the event delegation. If not captured, the event from each element bubbles up, and we can catch it.