TIL how to remove a event listener
POSTED ON:
Maybe you have a situation where you only want the event to fire once.
To Remove the Event #
const removeEventOffElement = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
const testFunction = () => console.log('My function has been called');
document.body.addEventListener('click', testFunction);// Call remove method
removeEventOffElement(document.body, 'click', fn);
To turn off the event after it's fired #
const myButton = document.getElementById("myBtn");
const myClickFunction = () => {
console.log('this click will only get called once')
}
myButton.addEventListener('click', myClickHandler, {
once: true,
});
REFERENCE:
21 Useful JavaScript Snippets For Everyday Development
Related TILs
Tagged: js