Update addMultipleEvents.md
This commit is contained in:
committed by
GitHub
parent
a712edbd19
commit
fdc7cb02b9
@ -1,24 +1,22 @@
|
|||||||
---
|
---
|
||||||
title: addMultipleEvents
|
title: addMultipleListeners
|
||||||
tags: JavaScript, Browser, Events, beginner
|
tags: browser,event,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
Add multiple event listener to an element.
|
Add multiple event listeners with the same handler to an element.
|
||||||
|
|
||||||
- Use <code>Array.prototype.forEach()</code> and <code>EventTarget.addEventListener()</code> to add multiples event listener with an assigned callback function to an element.
|
- Use `Array.prototype.forEach()` and `EventTarget.addEventListener()` to add multiple event listeners with an assigned callback function to an element.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const addMultipleEvents = (el, evts) => {
|
const addMultipleListeners = (el, types, listener, options, useCapture) => {
|
||||||
evts.forEach(evt => el.addEventListener(evt.name, evt.fn, false));
|
types.forEach(type => el.addEventListener(type, listener, options, useCapture));
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
addMultipleEvents(document.querySelector('.textInput'),
|
addMultipleListeners(
|
||||||
[
|
document.querySelector('.my-element'),
|
||||||
{name: 'mousedown', fn: () => console.log('mousedown event')},
|
['click', 'mousedown'],
|
||||||
{name: 'touchstart', fn: () => console.log('touchstart event')},
|
() => { console.log('hello!') }
|
||||||
{name: 'change', fn: () => console.log('change event')}
|
|
||||||
]
|
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user