Quick Wins with Code: Event Delegation
A quick look at using event delegation instead of placing multiple event listeners on a page.
Imagine a web page adorned with a lake of buttons. Each one of those buttons does something beautiful and life changing.
How do you make each of those buttons do something unique?
With event listeners! Any target button with an event listener on it will patiently wait for some designated event to occur, and then run some code.
Let’s say there are twenty buttons. Do you really want to write out twenty event listeners in our code? Nope. Don’t do it.
And you may think, “Oh, I’ll just loop through all the buttons and put an event listener on each one. That way, it won’t be as much code on the page.”
That may produce fewer lines of code, but it doesn’t change the fact that you still just created twenty separate event listeners. That many listeners should leave a bad code smell in your nose.
Enter event delegation.
The idea behind event delegation is to put one event listener on a common ancestor of all the elements you’re trying to listen to. Then, by using the
event object that you have access to inside of event listeners, you can check for what is being clicked, and then do something more specific based on that information.
Here’s an example:
Based on that HTML, let’s say my goal is to change the background color of the
<body> element on my web page, based on the specific
<li> I click on.
I could do that with multiple event listeners like this:
Or, I could use event delegation.
Again, the magic here is the use of the
event object, which we have access to inside the callback function of our listener.
event object has all sorts of useful properties about the event that just triggered the listener. One of those is
event.target, which tells me what HTML element in the DOM my event occurred on. With that, I can figure out what was clicked, and do something unique to that element.
That’s really all you need to know to be dangerous with this pattern.
Thanks for reading! 😄 Check out some of my other articles at quickwinswithcode.com