Create an one-time event handler
Sometimes we want a given event of an element to happen once. Usually, it can be done by attaching a handler which removes itself:
const handler = (e) => {
element.removeEventListener('click', handler);
};
element.addEventListener('click', handler);
We can use a named function expression to shorten the code a little bit:
element.addEventListener('click', function handler(e) {
e.currentTarget.removeEventListener(e.type, handler);
});
However, the
modern browsers provide the new
`once`
option that makes things easier. We don't have to track the reference of the handler anymore.
element.addEventListener(
'click',
(e) => {
},
{
once: true,
}
);