Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('touchstart', function (e) {
     closePopupOnClick(e, popup);
});

but this does not actually remove the event listener. If I put the addEventListener code in a function and pass that function into the the removeEventListener it will not work bc you cannot pass params into the function. Anyone know how to do this?

like image 964
FairyQueen Avatar asked Feb 26 '13 22:02

FairyQueen


People also ask

Can you remove an event listener JavaScript?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

How do I remove all event listeners from an element?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

How do I remove event listener in react?

Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.


1 Answers

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', function myListener(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

function listenerGenerator(popup) {
    return function (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.

like image 54
Paul S. Avatar answered Sep 20 '22 12:09

Paul S.