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.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.