Sometimes, we want to call removeEventListener with an anonymous function with JavaScript.
In this article, we’ll look at how to call removeEventListener with an anonymous function with JavaScript.
How to call removeEventListener with an anonymous function with JavaScript?
To call removeEventListener with an anonymous function with JavaScript, we assign the anonymous event listener function to a variable and call addEventListener
and removeEventListener
with the variable.
For instance, we write
const onScroll = () => {
//...
};
document.body.addEventListener("scroll", onScroll, false);
setTimeout(() => {
document.body.removeEventListener("scroll", onScroll, false);
}, 3000);
to call addEventListener
to add the onScroll
function as the scroll body element’s scroll event handler.
Then we call removeEventListener
in the setTimeout
callback that to remove the onScroll
function as the body element’s scroll event handler.
Conclusion
To call removeEventListener with an anonymous function with JavaScript, we assign the anonymous event listener function to a variable and call addEventListener
and removeEventListener
with the variable.