Remove event listener if I know only element and event

- 1 answer

Ad

Is there a way to remove event listener if I know only element and event, but don't know a function?

Something like:

var foo = getElementById("foo");
foo.removeEventListener('click');
Ad

Answer

Ad

Pure JS methods

There is no way to detach an event listener without having a reference to its listener method.

Method definition requires listener to be specified.

JS with modifications

It is possible to use some sort of custom functions like this:

function addEventListenerAndRemember(element, type, listener, useCapture)
{
    if (!element.myEvents) element.myEvents = {};
    if (!element.myEvents[type]) element.myEvents[type] = [];

    element.myEvents[type].push(listener);

    element.addEventListener(type, listener, useCapture || false);
}

function removeAllEventListener(element, type)
{
    element.myEvents.forEach(function() {
        element.myEvents[type].forEach(function(listener) {
            element.removeEventListener(type, listener);
        });
        element.myEvents[type] = [];
    });
}

I am not sure that this code works - it is just an example for demonstrating the idea.
You can also wrap these methods to addEventListener and override the default behaviour. Just like:

Element.prototype.addEventListenerBase = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(type, listener, useCapture) {
    // do the same
};

jQuery method

As for me, using jQuery library looks like the most clear solution here.

You will be able to attach an event this way:

$("#foo").on('click', function() {

});

and detach it in a simple way:

$("#foo").off('click');
Ad
source: stackoverflow.com
Ad