loading...

Event Delegation with JavaScript (In Simple Terms)

laurentcodes profile image Laurent Updated on ・2 min read

Event Delegation can be said to be a way of adding event listeners where you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.

This is particularly useful when we are dealing with elements that are dynamically added to the DOM, i.e they are not present when the page is initially loaded.

I recently worked on a project where I had to add list items to a page from a script, and each item needed some interaction, after trying to just target each list item unsuccessfully I decided to make a research and then I saw event delegation (mind you, I have come across this in a course before, but it didn't stick).

Anyways i started playing around with the concept and eventually got a hang of the terms and methodology and so I want to put it into writing here.

Using the below example: I have to access <li> tags in a <ul> tag with JavaScript and each <li> needs an event listener for the'click', event.
What I did was add the event listener to the <ul>

So:

ul.addEventListener('click', (e) => {
  console.log(e.target)
})

What this does is:

  1. The event listener is added to the ul element.
  2. An event parameter is passed in (e)
  3. Using the e parameter we can now access the target element (i.e the exact element being clicked in this case using e.target.
  4. When each li is clicked we get different values for e.target, this is to show that each li has it's own event listener now and we can do what we want with them.

I tried to make this as simple enough for beginners like me so I really hope it is understandable.

`

Discussion

pic
Editor guide