Skip to content Skip to sidebar Skip to footer

How To Remove An Event Listener In Javascript?

I am wondering how can I remove an event listener after adding one, the way you use on and off in jquery? document.removeEventListener('touchstart'); document.addEventListener('tou

Solution 1:

Put the listener as a variable and attach via .addEventListener

var myListener = function (e) {
    closePopupOnClick(e, popup);
};
document.addEventListener('touchstart', myListener, true);

then pass it again when removing with .removeEventListener

document.removeEventListener('touchstart', myListener);

If you're not in strict mode you can make a listener remove itself with arguments.callee

document.addEventListener('touchstart', function (e) {
    closePopupOnClick(e, popup);
    document.removeEventListener('touchstart', arguments.callee);
}, true);

If you are in strict mode, you have to use a named function expression if you want a function to remove itself

document.addEventListener('touchstart', functionmyListener(e) {
    closePopupOnClick(e, popup);
    document.removeEventListener('touchstart', myListener);
}, true);

If you want to use variables in the listener that may be changed by something (e.g. a loop), then you can write a generator function, for instance

functionlistenerGenerator(popup) {
    returnfunction (e) {
        closePopupOnClick(e, popup);
    };
}

Now you can create the listener with listenerGenerator(popup) and it will scope the popup variable. Note that if popup is an Object, it will be ByRef and therefore may still be subject to changes.

Solution 2:

I think a good way to do this is to add an Event yourself and then call

event.stopImmediatePropagation()

for example:

htmlElement.addEventListener('touchstart', (event) => event.stopImmediatePropagation());

In Chrome there are features like

htmlElement.removeAllListeners()

which probably remove the Listener for real. But i think it is not a wise solution because it does not seem to be well supported by other Browsers.

Post a Comment for "How To Remove An Event Listener In Javascript?"