When should removeEventListener be used?

As a bit of further background, events started as inline HTML attributes:

<div onclick="doSomething()"></div>

The trouble with that is that the function had no idea about from where the event was being triggered, so you would have to throw in an event parameter.

Other problems are that the HTML code ends up getting covered in JavaScript code. Companies were having trouble because scripting updates resulted in the HTML code needing to be updated too.

Eventually a separation of concerns occurred, with HTML being restricted to the HTML pages, CSS being restricted to the CSS pages, and JS being restricted to the JS pages.

This is where the traditional event methods became popular to use.

function doSomething(evt) {
  ...
}
button.onclick = doSomething;

They worked well for a while, but had trouble in that only one of each type of event was allowed. It wasn’t possible to have multiple click events on the same element.

button.onclick = doSomething; // doesn't work, is overwritten by the doSomething function
button.onclick = doSomethingElse;

Instead you would need to have a separate event handler that controlled the different things to occur.

button.onclick = function buttonClickHandler(evt) {
    doSomething(evt);
    doSomethingElse(evt);
};

That worked for a while but became annoying to manage. It was especially annoying when different sets of code wanted to do something with the same element.

That brings us to addEventListener which is the modern way of dealing with things, as it solves all of those earlier problems.

With addEventListener you can easily have multiple sets of the same event being listened for at the same time.

button.addEventListener("click", doSomething);
button.addEventListener("click", doSomethingElse);

If you want to delve deeper into the history of events and all of the troubles and solutions with them, excellent details have been provided by ppk at their quirksmode website.

3 Likes