Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active August 26, 2021 18:59
Show Gist options
  • Save LeanSeverino1022/3af60726099e28ff7b9f786d2234d894 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/3af60726099e28ff7b9f786d2234d894 to your computer and use it in GitHub Desktop.
event delegation pure js #vanillajs

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:

  1. https://gomakethings.com/why-event-delegation-is-a-better-way-to-listen-for-events-in-vanilla-js/
  2. 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

Dynamically rendered elements

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment