When multiple event listeners do the same thing, you don’t want to repeat yourself and write the same function twice. In our example we want to attach both click and keydown to an element.

The first and most obvious approach you could think of is probably this:


myElement.addEventListener('click keydown', () => {
	// Do something
});

And it doesn’t work, because each event type requires its own event listener.

Solution:

We’re going to put the list of our events into an array and loop through them, adding its listener to our element on each iteration:


["click", "keydown"].forEach(event => {
   // Do something
});

Alternative solution:

The alternative solution is to put all functions in a single named function and pass it into each event listener:


var muFunction = event => {
    // Do something
};

window.addEventListener('click', muFunction, false);
window.addEventListener('keydown', muFunction, false);