Remove event listener from element

JavaScript, Browser, Event · Oct 21, 2020

Removes an event listener from an element.

  • Use EventTarget.removeEventListener() to remove an event listener from an element.
  • Omit the fourth argument opts to use false or specify it based on the options used when the event listener was added.
const off = (el, evt, fn, opts = false) =>
  el.removeEventListener(evt, fn, opts);
const fn = () => console.log('!');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page

More like this

  • JavaScript Event Handling

    Event handling needs to be done right in JavaScript. Pick up some tips and tricks to create a better user experience.

    Collection · 15 snippets

  • Remove event listeners from target

    Detaches an event listener from all the provided targets.

    JavaScript, Browser · Apr 22, 2021

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020

  • Add event listener to element

    Adds an event listener to an element with the ability to use event delegation.

    JavaScript, Browser · Oct 21, 2020