Vanilla JS add event listener on multiple elements

β€” 6 minute read

permalink

So the other day Svondervoort asked in the comments why I was using the global JavaScript event listener instead of adding it to the specific element.

I thought it was an excellent question, and to be honest, it's one of these things that also have a preferred way of working.

So in Vanilla JavaScript, there are multiple ways of adding event listeners to elements. So let's look at some Vanilla JS examples for the addEventListener method and apply it to HTML elements.

Add event listener to one single element permalink

So ofcourse we can use add event listener directly on an HTML element using for example the following code:

var btn = document.getElementById('btn-section-3');
btn.addEventListener('click', function(event) {
console.time('id');
event.preventDefault();
var element = document.getElementById(event.target.dataset.target);
element.scrollIntoView();
console.timeEnd('id');
});

As you can see, very easy to understand, we get the element based on its ID CSS selector and then use addEventListener to listen for the click event.

Then we start a performance timer to keep track of the speed.

We then do a simple scrollIntoView to have some animation.

This is a good way of binding to the element, but it's very narrow. You can only attach to that specific element, and it will stop there. There is also no way to bind to multiple elements.

Vanilla JS use addEventListener in a for loop permalink

So how can we use addeventlistener on multiple elements?

We can use a for-loop. There are many ways to loop in JavaScript, but let's try this one:

document.querySelectorAll('.more-class').forEach(item => {
item.addEventListener('click', event => {
console.time('more');
event.preventDefault();
var element = document.getElementById(event.target.dataset.target);
element.scrollIntoView();
console.timeEnd('more');
});
});

So the same thing as above, we use querySelectorAll to get all items that match the class more-class and loop through the elements. Then we use addEventListener and add it again to each element.

Keep in mind we are only timing the click. We also used the forEach-loop, which takes up time!

Add event listener to multiple items using event bubbling permalink

The method I use most is called event bubbling.

"Event bubbling" means that every DOM element will have an event listener and bubbles through each child. On the event we have to filter out which of the elements we want to react too.

At first, this method seems very slow and sloppy, but it's one of the most versatile methods and quick!

document.addEventListener('click', function(event) {
if (!event.target.matches('.btn-scroll-into')) return;
console.time('bubbling');
event.preventDefault();
var element = document.getElementById(event.target.dataset.target);
element.scrollIntoView();
console.timeEnd('bubbling');
});

So here we use addEventListener on all elements to listen to clicks anywhere in the DOM. The JavaScript code will check through all the children if the target elements match the class btn-scroll-into.

If this is not the case we return;. The return will stop the function. If not, we do the same code we did before.

Which one should you use? permalink

I honestly think it's up to you. When I havre to listen to events on many elements, I prefer the event bubbling method because it is easiest to apply for me without having to worry about performance. But you will see me use a variety of these in projects.

I hope you learned something about adding event listeners across many elements and hope you can use these in your upcoming Vanilla JavaScript projects.

Try the addEventListener code examples in this Codepen: permalink

See the Pen Vanilla JavaScript addEventListener on Multiple elements by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter