Events are an important part of the modern web. The browser fires off events like clicks, key presses, and mouse movements, and we can listen for these events to then execute code.
Adding a single event listener is easy, but adding multiple event listeners can be a little more involved.
In this post, we're going to look at the best way to add multiple event listeners.
Adding Single Event Listener
Before we learn about adding multiple event listeners, we need to understand how to add a single event listener.
First, query for the element that you want to add an event listener to by using document.querySelector()
:
JAVASCRIPTconst element = document.querySelector(".element");
Now, simple add an event listener to it. Let's add a simple click listener:
JAVASCRIPTconst element = document.querySelector(".element");
element.addEventListener("click", () => {
console.log("Clicked!");
});
Great, now let's see how we can adapt this to support multiple listeners.
Adding Event Listener to Multiple Elements
In the same way we queried for a single event listener, let's query for multiple event listeners.
This time, let's use document.querySelectorAll()
which returns a list of elements.
JAVASCRIPTconst elements = document.querySelectorAll(".elements");
Now, let's use forEach
to add an event listener to each element:
JAVASCRIPTconst elements = document.querySelectorAll(".elements");
elements.forEach(element => {
element.addEventListener("click", () => {
console.log("Clicked!");
});
});
If you have different elements that you want to add event listeners to, you can first create an array first, then use forEach
on that array.
JAVASCRIPTconst element1 = document.querySelector(".element1");
const element2 = document.querySelector(".element2");
const element3 = document.querySelector(".element3");
const elements = [element1, element2, element3];
elements.forEach(element => {
element.addEventListener("click", () => {
console.log("Clicked!");
});
});
Conclusion
In this post, we've seen how to add a single event listener to an element, and how to add multiple event listeners to multiple elements.
The process is the same, simply query for the element or elements, then add an event listener to each individual element.
Hopefully, this post has helped you get familiar with adding event listeners to elements.
Thanks for reading!
- Getting Started with Solid
- Best Visual Studio Code Extensions for 2022
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API