Use vanilla JavaScript for event delegation in the browser

One of my favorite thingsjQueryYes (yes?) Event delegation. in particular.on()method.

We choose oneDOMElement and then we use.on()An event handler attached to a specific child element of the element.

Why is this useful? Because if you are dynamically adding elements to the DOM, a single event listener will pass.on()Will work on all children, even children added to the DOM after registering the event handler.

Suppose you have a table. Inside the table, we have a set of rows, and each row has a 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(…) } })

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

How can we replicate the same functionality using vanilla JavaScript?

We create aonFunction with wrapped selector, an event type (a'click'For example string), a sub-selector string that will match the descendants of the wrapped selector. In this function, we first create a loop, and then add an event listener to each element that matches the wrapper selector (so it can be applied to multiple wrapper selectors).

Then, if the target of the event matches our child selector (the third parameter of the function), we will call the callback function passed as the fourth parameter and pass 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 call this function:

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

Now when we click on the matching element.module.completeunderulSelector, the code in the function we passed will run, and we can extract the clicked item reference from itevent.target.

Download mine for freeJavaScript beginner's manual


More js tutorials: