What is event delegation in JavaScript?

Event delegation is one of the most potent events handling patterns. It allows users to append a single event listener to a parent element that adds it to all of its present and future descendants that match a selector.

The main steps involve:

  1. Add a handler on a container
  2. Add the event.target source element on the handler
  3. Handle the event

Code

Let’s append a handler on the following table that changes the font color to grey when a user clicks on the text.

  • To make use of Event Delegation, first create an HTML file.
  • In the javascript file/script tag make use of the function document.getElementById and give it the id of the table that event delegation needs to be applied to.
  • Use addEventListener and pass the parameter “onclick” and function(e) into it. This in-built function waits for an event to take place and, as soon as the event takes place ( i.e., a click or hover), the listener calls the function passed to it.
  • Then for e.target, suggest what property of the cell you want to change.
  • This function will automatically be applied to all the cells in the specified table.

Similarly, handlers can be applied to multiple elements throughout the document. Event delegation helps you to avoid redundant code and makes it shorter and easier to read.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved