Skip to main content Accessibility Feedback

Listening to multiple events in vanilla JS

A few weeks back, we looked at how to attach multiple elements to a single event listener in vanilla JavaScript.

Today, let’s look at how to run the same code for multiple types of events without having to duplicate your code.

Each event needs its own listener

In vanilla JavaScript, each event type requires its own event listener. Unfortunately, you can’t pass in multiple events to a single listener like you might in jQuery and other frameworks.

For example, you cannot do this:

document.addEventListener('click mouseover', function (event) {
    // do something...
}, false);

But… by using a named function and passing that into your event listener, you can avoid having to write the same code over and over again.

// Setup our function to run on various events
var someFunction = function (event) {
    // Do something...
};

// Add our event listeners
window.addEventListener('click', someFunction, false);
window.addEventListener('mouseover', someFunction, false);

addEventListener automatically passes the event object into your function as an argument.