/html-dom /Basic
GitHub 4932★

Create one time event handler

1. Use the once option

When attach a handler to given event, you can pass { once: true } to the last parameter of the addEventListener method:

const handler = function (e) {
// The event handler
};

ele.addEventListener('event-name', handler, { once: true });

Note that this option isn't supported in IE.

2. Self-remove the handler

const handler = function (e) {
// The event handler
// Do something ...

// Remove the handler
e.target.removeEventListener(e.type, handler);
};

ele.addEventListener('event-name', handler);

Use case

See also

Follow me on and to get more useful contents.