Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
event delegation
js

What is event delegation in JavaScript?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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.

RELATED TAGS

javascript
event delegation
js
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring