Event Delegation
Bubbling makes it possible to do one of the most useful tricks, event delegation. When there is a group of elements with events that need to be handled in the same way, then one handler should be added to their common ancestor, instead of adding a handler to each element. Using the event.target
property, you can get a reference to the target element, figure out on which child the event occurred and then handle it.
Let's look at an example of delegation. Create the <div>
element, add an arbitrary number of buttons to it, for example 100, and for each of them register a click event listener with handleButtonClick
function.

The problem is that you have a hundred event listeners. They all point to the same listener function, but there are 100 listeners overall. What if you move all listeners to a common ancestor, the <div>
element?

Now there is only one click event handler, and the browser does not need to store 100 different listeners in memory. That is, delegation is reduced to three simple steps.
- Determine the common ancestor for a group of elements to monitor events.
- On the parent element, register a handler for the event that you want to monitor in the group of elements.
- In the handler, use
event.target
to select the target element.
This approach simplifies the initialization of listeners for the same type of elements. You can add, remove or modify elements, without manually adding or removing event handlers.
Color palette
Let’s make a color palette with the ability to select a color by clicking and to display the selected color. Instead of assigning a handler to each palette element, which can be numerous, add one listener to the common ancestor div.color-palette
. In the click event handler, use event.target
to find the element on which the event occurred and the associated color, which will be stored in the data-color
attribute.
Be sure to check the click target – it must be a button, as you do not want to handle clicks in a container element. For an element type check, use the nodeName
property.