Skip to content

Event delegation in the browser using vanilla JavaScript

New Course Coming Soon:

Get Really Good at Git

One of my favorite things from jQuery is (was?) event delegation. In particular the .on() method.

We select a DOM element, and then we use .on() to attach an event handler that’s executed on a particular child of that element.

Why is this useful? Because if you’re adding elements dynamically to the DOM, a single event listener registered through .on() will work on all children, even the ones that are added to the DOM after you registered the event handler.

Suppose you have a table. Inside the table, we have a set of rows, and each row has an button with a click handler.

You register an event listener when the DOM loads:

document.addEventListener('DOMContentLoaded', () => {
  const buttons = document.querySelectorAll('button')

  for (const button of buttons) {
    button.addEventListener(...)
  }
})

But if we add a new row to the table, we must then also remember to register a new event listener.

How can we replicate the same functionality using vanilla JavaScript?

We create a on function that takes a wrapper selector, an event type (a 'click' string for example), a child selector string, that will match descendants of the wrapper selector. In this function, we first create a loop, and we add an event listener to each element that matches our wrapper selector (so it can apply to more than one wrapper selector).

Then if the target of the event matches our child selector (third parameter of the function), we call the callback function passed as the 4th parameter, passing the event:

const on = (selector, eventType, childSelector, eventHandler) => {
  const elements = document.querySelectorAll(selector)
  for (element of elements) {
    element.addEventListener(eventType, eventOnElement => {
      if (eventOnElement.target.matches(childSelector)) {
        eventHandler(eventOnElement)
      }
    })
  }
}

This is how we can invoke this function:

on('ul', 'click', '.module.complete', event => {
  const item = event.target
  //...your event handler
})

Now when we click on an element that matches .module.complete under the ul selector, the code in the function we pass in will be ran, and we can extract the clicked item reference from event.target.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: