With event delegation, you bind an event to the topmost element (in the case of the DOM, that's the document element), capture every event, and run the registered callback after determining whether it's relevant.

We're going to look for the closest target, and if we find one, execute a piece of code.

Cleaning things up

Next to selecting DOM elements, listening to events is one of the most common things we'll be doing when building web apps. The setup for event delegation requires some boilerplate, so let's wrap it up in a listen function.

Why event delegation?

The main benefit of delegate event listeners is that you don't need to bind and unbind event listeners when the DOM changes. With addEventListener, you need to register a new event listener whenever an a gets added to the DOM. With event delegation, you set it once and can forget about it.

Event delegation can also positively affect performance. While this approach will get triggered more often (every click triggers the event listener, not just relevant ones), you only need to register a single listener, which has a more significant impact on performance.

JavaScript Framework Diet

JavaScript frameworks are great, but overused. Adding small bits of interactivity to an interface shouldn't mean installing kilobytes of dependencies or introducing complex build tools.

It's time for a diet. I'm challenging you to build something without a framework, or follow along and learn something along the way.