Skip to main content Accessibility Feedback

How many event listeners is too many in JavaScript?

One of the first things I teach my JavaScript students when learning about events is event delegation.

When you have multiple elements that all react to the same type of event, you can listen for that event on a parent element, and filter out elements that aren’t the ones you’re looking for. It’s easier to author, and better for performance (fewer listeners in the browser’s memory).

<button class="click-me">Click Me</button>
<button>Do NOT Click Me</button>
<button class="click-me">Click Me</button>
document.body.addEventListener('click', function (event) {

	// Only run on .click-me elements
	if (!event.target.matches('button.click-me')) return;

	// Do stuff...

});

The other day, one of my students asked me…

Is there a number of event listeners that’s considered “too many”?

Not really!

I think the React model of “an individual listener on every single interactive element” is bad, but there’s not some magic “that’s too many” number I can give you.

Generally speaking, I think in terms of components or libraries: one event of each type within a specific component.

If I’m listening for click events, I’ll do that once in a specific library. If only one element needs it, I attach directly to that element. If not, I delegate.

If other libraries or components also use a click event, I let them manage that separately.