Vanilla JavaScript event listener on Multiple elements
Tags: javascript
Published: 2020-04-30 06:22:04

So the other day svondervoort asked [in the comments](https://daily-dev-tips.com/posts/animated-hamburger-side-menu-%F0%9F%8D%94/#heading-2-comments-on-this-page) why I was using the global `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.

## Add event listener to single element

So of-course we can add a `event listener` directly to a element using the following code:

```js
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` and then use `addEventListener` to listen for the click event.
Then we start a [performance timer](https://daily-dev-tips.com/posts/vanilla-javascript-timing-functions/) to keep track of the speed.
We then do a simple [scrollIntoView](http://daily-dev-tips.com/posts/vanilla-javascript-element-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 that to multiple elements now.

## Add event listener in a for loop

So how can we add this `event listener` to multiple elements?

We can use a `for loop`, there are many ways to loop, but let's try this one:

```js
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 with the class `more-class` and loop through them, we then use `addEventListener` again and do the same thing.

> Keep in mind we are only timing the click; we also used the `forEach loop` here, which takes up time!

## Event listener using event bubbling

The option I use the most is the one using `event bubbling`.

`Event bubbling` means that every `DOM` element will have a listener and bubbles through each child, we have to filter out which one 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!

```js
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` to listen to all clicks on the `document`. JavaScript will now go through all the children, and we check if the target matches the class `btn-scroll-into`, if this is not the case we `return;`. The return will stop this function.
If not, we do the same code we did before.

## Which one should you use?

I honestly think it's up to you; I prefer the `event bubbling` method myself because it's the most versatile, but you will see me use a variety of these in projects.

I hope you learned something about adding `event listeners` and hope you can use these in your awesome projects.

Feel free to play around with this Codepen:

<p class="codepen" data-height="265" data-theme-id="dark" data-default-tab="js,result" data-user="rebelchris" data-slug-hash="jObLOqw" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Vanilla JavaScript event listener on Multiple elements">
  <span>See the Pen <a href="https://codepen.io/rebelchris/pen/jObLOqw">
  Vanilla JavaScript event listener on Multiple elements</a> by Chris Bongers (<a href="https://codepen.io/rebelchris">@rebelchris</a>)
  on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

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

Thank you for reading my blog, feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)