Removing anonymous event listeners

Warning This article was written over six months ago, and may contain outdated information.

I recently ran into a problem involving the removeEventListener() method, which caused me a good half an hour of confusion before a lightbulb appeared above my head and I was enlightened by a solution — a solution which, it must be said, is very obvious in hindsight. So doubtless many people know this already, but I’m recording it here along with another approach I thought of afterwards, in the hope that they may be useful to someone in the future.

The issue at hand is this: to add an event listener to an element, you use the addEventListener() method with the type of event, and the name of the listener — most often, a call to a pre‐defined function:

el.addEventListener('click', foo);

When you want to remove the listener, you use the removeEventListener() method, with the same arguments to ensure that only the specified event and listener combination is removed:

el.removeEventListener('click', foo);

Simple. But it becomes less straightforward when you use an anonymous function as the listener, perhaps because you want to call another function and pass arguments to it:

el.addEventListener('click', function() {
foo(bar,baz);
});

In order to remove this listener you have to know the name of it. But it’s anonymous! What are we to do? The answer is ridiculously simple: don’t use anonymous functions. You could instead name the function in the listener, then remove it when the function has run:

These solutions seem so obvious that I debated whether it was worth recording them here, but in my searches I couldn’t find them listed anywhere; I hope that by writing them up I’ll save someone some searching time in the future.

Related

3 comments on “Removing anonymous event listeners”

The final suggestion of assigning the function to a variable won’t work in all cases. Mainly because “_func.name == undefined”.