Remove All Event Listeners of Specific Type

JavascriptEvents

Javascript Problem Overview


I want to remove all event listeners of a specific type that were added using addEventListener(). All the resources I'm seeing are saying you need to do this:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown',specific_function);

But I want to be able to clear it without knowing what it is currently, like this:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown');

Javascript Solutions


Solution 1 - Javascript

That is not possible without intercepting addEventListener calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.

The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.

Note: This will also remove listeners on element's children.

var el = document.getElementById('el-id'),
    elClone = el.cloneNode(true);

el.parentNode.replaceChild(elClone, el);

Solution 2 - Javascript

If your only goal by removing the listeners is to stop them from running, you can add an event listener to the window capturing and canceling all events of the given type:

window.addEventListener(type, function(event) {
    event.stopImmediatePropagation();
}, true);

Passing in true for the third parameter causes the event to be captured on the way down. Stopping propagation means that the event never reaches the listeners that are listening for it.

Keep in mind though that this has very limited use as you can't add new listeners for the given type (they will all be blocked). There are ways to get around this somewhat, e.g., by firing a new kind of event that only your listeners would know to listen for. Here is how you can do that:

window.addEventListener('click', function (event) {
    // (note: not cross-browser)
    var event2 = new CustomEvent('click2', {detail: {original: event}});
    event.target.dispatchEvent(event2);
    event.stopPropagation();
}, true);

element.addEventListener('click2', function(event) {
    if (event.detail && event.detail.original) {
        event = event.detail.original
    }
    // Do something with event
});

However, note that this may not work as well for fast events like mousemove, given that the re-dispatching of the event introduces a delay.

Better would be to just keep track of the listeners added in the first place, as outlined in Martin Wantke's answer, if you need to do this.

Solution 3 - Javascript

You must override EventTarget.prototype.addEventListener to build an trap function for logging all 'add listener' calls. Something like this:

var _listeners = [];

EventTarget.prototype.addEventListenerBase = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener)
{
    _listeners.push({target: this, type: type, listener: listener});
    this.addEventListenerBase(type, listener);
};

Then you can build an EventTarget.prototype.removeEventListeners:

EventTarget.prototype.removeEventListeners = function(targetType)
{
    for(var index = 0; index != _listeners.length; index++)
    {
        var item = _listeners[index];
        
        var target = item.target;
        var type = item.type;
        var listener = item.listener;
        
        if(target == this && type == targetType)
        {
            this.removeEventListener(type, listener);
        }
    }
}

In ES6 you can use a Symbol, to hide the original function and the list of all added listener directly in the instantiated object self.

(function()
{
    let target = EventTarget.prototype;
    let functionName = 'addEventListener';
    let func = target[functionName];

    let symbolHidden = Symbol('hidden');
    
    function hidden(instance)
    {
        if(instance[symbolHidden] === undefined)
        {
            let area = {};
            instance[symbolHidden] = area;
            return area;
        }
        
        return instance[symbolHidden];
    }
    
    function listenersFrom(instance)
    {
        let area = hidden(instance);
        if(!area.listeners) { area.listeners = []; }
        return area.listeners;
    }
    
    target[functionName] = function(type, listener)
    {
        let listeners = listenersFrom(this);
        
        listeners.push({ type, listener });
        
        func.apply(this, [type, listener]);
    };
    
    target['removeEventListeners'] = function(targetType)
    {
        let self = this;
    
        let listeners = listenersFrom(this);
        let removed = [];
        
        listeners.forEach(item =>
        {
            let type = item.type;
            let listener = item.listener;
            
            if(type == targetType)
            {
                self.removeEventListener(type, listener);
            }
        });
    };
})();

You can test this code with this little snipper:

document.addEventListener("DOMContentLoaded", event => { console.log('event 1'); });
document.addEventListener("DOMContentLoaded", event => { console.log('event 2'); });
document.addEventListener("click", event => { console.log('click event'); });

document.dispatchEvent(new Event('DOMContentLoaded'));
document.removeEventListeners('DOMContentLoaded');
document.dispatchEvent(new Event('DOMContentLoaded'));
// click event still works, just do a click in the browser

Solution 4 - Javascript

Remove all listeners on a global event

element.onmousedown = null;

now you can go back to adding event listeners via

element.addEventListener('mousedown', handler, ...);

This solution only works on "Global" events. Custom events won't work. Here's a list of all global events: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers

Solution 5 - Javascript

I know this is old, but I had a similar issue with no real answers, where I wanted to remove all keydown event listeners from the document. Instead of removing them, I override the addEventListener to ignore them before they were even added, similar to Toms answer above, by adding this before any other scripts are loaded:

<script type="text/javascript">
    var current = document.addEventListener;
    document.addEventListener = function (type, listener) {
        if(type =="keydown")
        {
            //do nothing
        }
        else
        {
            var args = [];
            args[0] = type;
            args[1] = listener;
            current.apply(this, args);
        }
    };
</script>

Solution 6 - Javascript

So this function gets rid of most of a specified listener type on an element:

function removeListenersFromElement(element, listenerType){
  const listeners = getEventListeners(element)[listenerType];
  let l = listeners.length;
  for(let i = l-1; i >=0; i--){
    removeEventListener(listenerType, listeners[i].listener);
  }
 }

There have been a few rare exceptions where one can't be removed for some reason.

Solution 7 - Javascript

A modern way to remove event listeners without referencing the original function is to use AbortController. A caveat being that you can only abort the listeners that you added yourself.

const buttonOne = document.querySelector('#button-one');
const buttonTwo = document.querySelector('#button-two');
const abortController = new AbortController();

// Add multiple click event listeners to button one
buttonOne.addEventListener(
  'click',
  () => alert('First'),
  { signal: abortController.signal }
);

buttonOne.addEventListener(
  'click',
  () => alert('Second'),
  { signal: abortController.signal }
);

// Add listener to remove first button's listeners
buttonTwo.addEventListener(
  'click',
  () => abortController.abort()
);

<p>The first button will fire two alert dialogs when clicked. Click the second button to remove those listeners from the first button.</p>

<button type="button" id="button-one">Click for alerts</button>
<button type="button" id="button-two">Remove listeners</button>

Solution 8 - Javascript

Remove all listeners in element by one js line:

element.parentNode.innerHTML += '';

Solution 9 - Javascript

In the extreme case of not knowing which callback is attached to a window listener, an handler can be wrapper around window addEventListener and a variable can store ever listeners to properly remove each one of those through a removeAllEventListener('scroll') for example.

var listeners = {};

var originalEventListener = window.addEventListener;
window.addEventListener = function(type, fn, options) {
    if (!listeners[type])
        listeners[type] = [];

    listeners[type].push(fn);
    return originalEventListener(type, fn, options);
}

var removeAllEventListener = function(type) {
    if (!listeners[type] || !listeners[type].length)
        return;

    for (let i = 0; i < listeners[type].length; i++)
        window.removeEventListener(type, listeners[type][i]);
}

Solution 10 - Javascript

You cant remove a single event, but all? at once? just do

document.body.innerHTML = document.body.innerHTML

Solution 11 - Javascript

You could alternatively overwrite the 'yourElement.addEventListener()' method and use the '.apply()' method to execute the listener like normal, but intercepting the function in the process. Like:

<script type="text/javascript">
    
    var args = [];
    var orginalAddEvent = yourElement.addEventListener;

    yourElement.addEventListener = function() {
        //console.log(arguments);
        args[args.length] = arguments[0];
        args[args.length] = arguments[1];
        orginalAddEvent.apply(this, arguments);
    };

    function removeListeners() {
        for(var n=0;n<args.length;n+=2) {
            yourElement.removeEventListener(args[n], args[n+1]);
        }
    }

    removeListeners();

</script>

This script must be run on page load or it might not intercept all event listeners.

Make sure to remove the 'removeListeners()' call before using.

Solution 12 - Javascript

 var events = [event_1, event_2,event_3]  // your events

//make a for loop of your events and remove them all in a single instance

 for (let i in events){
    canvas_1.removeEventListener("mousedown", events[i], false)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJ SView Question on Stackoverflow
Solution 1 - JavascriptplalxView Answer on Stackoverflow
Solution 2 - JavascriptChris MiddletonView Answer on Stackoverflow
Solution 3 - JavascriptMartin WantkeView Answer on Stackoverflow
Solution 4 - JavascriptChris HayesView Answer on Stackoverflow
Solution 5 - JavascriptPaladinMatttView Answer on Stackoverflow
Solution 6 - JavascriptMike SrajView Answer on Stackoverflow
Solution 7 - JavascriptThomas HigginbothamView Answer on Stackoverflow
Solution 8 - JavascriptNazar VynnytskyiView Answer on Stackoverflow
Solution 9 - Javascriptyves amsellemView Answer on Stackoverflow
Solution 10 - JavascriptMcKabueView Answer on Stackoverflow
Solution 11 - JavascriptTom BurrisView Answer on Stackoverflow
Solution 12 - JavascriptSri HarshaView Answer on Stackoverflow