For example, if you wanted to open a modal when any button with the .modal-open class is clicked, and close modals when an element with the .close class is clicked, you would do this.
document.addEventListener('click', function (event) {
if (event.target.matches('.modal-open')) {
// Run your code to open a modal
}
if (event.target.matches('.close')) {
// Run your code to close a modal
}
}, false);
resources for learning:
- https://gomakethings.com/why-event-delegation-is-a-better-way-to-listen-for-events-in-vanilla-js/
- https://davidwalsh.name/event-delegate
I found this helpful when I had to have dynamically rendered elements.. remember gmail extension project- loading side-bar dynamically
If you attach an event listener to specific elements at the time the DOM loads, you’ll need to repeat that process if you add elements to the DOM later with JavaScript.
For example, let’s say you have a form where users can click a button to add additional text fields, and click a “remove me” button next to each field to remove it.
With a traditional approach, attaching listeners to specific elements, you would need to add a new listener every time you added a field. With event delegation, you can setup your listener once and not have to worry about it, since it checks selectors at time of click rather than when the DOM is initially rendered.