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 TypeScript
Getting Started with Solid
Getting Started with Express
Getting Started with Electron
How to Serve Static Files with Nginx and Docker
How to deploy a Deno app using Docker
How to deploy a Node app using Docker
Getting Started with Sass
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Getting Started with React
Getting Started with Vuex: Managing State in Vue
