removeEventListener() and anonymous functions

Davide Ramaglietta
2 min readNov 29, 2017

A short guide on the correct usage of removeEventListener()

Lately, I was trying to remove an event listener previously added from an element and it came out to be a proper riddle! I spent a good half an hour to find a solution, therefore I decided to write this article as a reminder for the future myself and for my colleagues which might face the same case.

Stop listening to unnecessary noises!

The EventTarget.removeEventListener() method removes from the EventTarget an event listener previously registered with EventTarget.addEventListener() (from MDN web docs).

The event listener to be removed is identified combining:

  • event type
  • event listener function itself
  • various optional options

For example, assuming we registered an event listener with the following statement:

element.addEventListener("keyup", handleKeyUp);

to stopping listening to the specific event, we simply execute:

element.removeEventListener("keyup", handleKeyUp);

In case some options were specified at the moment of registering the event, they must also match when removing the listener. Therefore, if we previously registered the following:

element.addEventListene…

--

--