DOM Removing event listeners

Download DOM for free


The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:

element.removeEventListener("mousemove", myFunction);

Everything (eventname, function, and options) in the removeEventListener must match the one set when adding the event listener to the element.

.bind with removeListener

using .bind on the function when adding an event listener will prevent the function from being removed, to actually remove the eventListener you can write:

function onEvent() {

var bindingOnEvent = onEvent.bind(this);

document.addEventListener('click', bindingOnEvent);


document.removeEventListener('click', bindingOnEvent);

listen to an event only once

Until once option is widely supported, we have to manually remove the even listener once the event is triggered for the first time.

This small helper will help us achieve this:

Object.prototype.listenOnce = Object.prototype.listenOnce ||
  function listenOnce(eventName, eventHandler, options) {
      var target = this;
      target.addEventListener(eventName, function(e) {
          target.removeEventListener(eventName, eventHandler, options);
      }, options);

var target = document.querySelector('#parent');
target.listenOnce("click", clickFunction, false);

*It is not a best practice to attach functions to the Object prototype, hence you can remove the first line of this code and add a target to it as a first param.

Triggering custom events