Hello, my name is: Amy

Explain event delegation

To describe how event delegation works I'll first explain the idea of event propagation, also known as the 'bubbling effect'. What this means is that any time you do something that can be registered as an event (click, mouseover, load, etc) those events will also be triggered to any of the parent elements.

In this below codepen, there are click events on both the <li>'s as well as the <ul>. If you click on the <a> link, you will see that there is also a click event registered in the <li> and <ul>.

See the Pen Event Delegations by Amy Etheredge (@theaemarie) on CodePen.

First thought might be that this is a bad thing, but knowing of how events travel up helps you figure out how to capture the events from below.

In our list example, instead of having to create an event listener for each list item (with the for loop that I used), using event delegation I can create just one event listener for the container, the <ul>. Which this setup, any time one of the <ul>'s children is clicked the event will bubble up to the <ul> container itself and perform the action.

Why is this useful? Event listeners have to be registered to each specific item in order to work, so if you are adding a <li> to the list after the fact and expect an event to trigger on it you'd have to also register a new event handler with each new element. In the pen above, clicking on the button to add a new list item will not create a alert for clicking on that item. The <ul> alert is still triggered as the event bubbles up.

Using event delegation allows you to add/remove elements from the DOM without needing to manage the individual listeners. If you need to know specifically which element was clicked on, there is a property on the event object that gets passed in called event.target. This will output where the event was actually triggered.