Event delegation in the browser using vanilla JavaScript
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
.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025