Files
30-seconds-of-code/snippets/addMultipleEvents.md
Isabelle Viktoria Maciohsek fdc7cb02b9 Update addMultipleEvents.md
2020-10-08 15:54:03 +03:00

23 lines
600 B
Markdown

---
title: addMultipleListeners
tags: browser,event,intermediate
---
Add multiple event listeners with the same handler to an element.
- Use `Array.prototype.forEach()` and `EventTarget.addEventListener()` to add multiple event listeners with an assigned callback function to an element.
```js
const addMultipleListeners = (el, types, listener, options, useCapture) => {
types.forEach(type => el.addEventListener(type, listener, options, useCapture));
}
```
```js
addMultipleListeners(
document.querySelector('.my-element'),
['click', 'mousedown'],
() => { console.log('hello!') }
);
```