JavaScript events are the catalysts behind most web functionality. Interacting with literally any website means firing away a ton of events. Have you ever thought about how these events get assigned? Are developers just tirelessly adding event functionality to every single element? What about dynamically created content, how do events get added to that? Well, there are a few different approaches to address these questions.

Nested Event Listeners

One approach is to assign an event listener every single time an element is created.

For our example code we will be creating buttons and adding event listeners to them. **Our goal is to change the colors of individual buttons on click. **Our starter HTML is just this:

<ul id="button-container">

</ul>

In our JavaScript file, we will be selecting the container, adding buttons to it by iterating over an array of colors, and appending each one to the container. This is arbitrary and just intended to mimic creating elements dynamically based on incoming data.

#event-delegation #javascript #javascript-events

The Art of JavaScript Event Delegation
1.40 GEEK