Update listenOnce.md

Use `{ once: true }` as `options` to make the listener run at most one time.
This commit is contained in:
Isabelle Viktoria Maciohsek
2020-08-10 13:52:27 +03:00
committed by GitHub
parent f8a3f6003e
commit c691a0b61a

View File

@ -1,26 +1,19 @@
---
title: listenOnce
tags: browser,event,closure,intermediate
tags: browser,event,beginner
---
Adds an event listener to an element that will only run the callback the first time the event is triggered.
Use `EventTarget.addEventListener()` to add an event listener to an element, storing the reference in a variable.
Use a condition to call `fn` only the first time the listener is triggered.
Use `EventTarget.addEventListener()` to add an event listener to an element, using `{ once: true }` as options to only run the given callback once.
```js
const listenOnce = (el, evt, fn) => {
let fired = false;
el.addEventListener(evt, (e) => {
if (!fired) fn(e);
fired = true;
});
};
const listenOnce = (el, evt, fn) => el.addEventListener(evt, fn, { once: true });
```
```js
listenOnce(
document.getElementById('my-id),
document.getElementById('my-id'),
'click',
() => console.log('Hello world')
); // 'Hello world' will only be logged on the first click