Removing javascript eventlisteners

I have the following javascript to activate sometime

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); 

but I am having problems removing the event listener when I do this

 document.removeEventListener('touchmove', function (e) { e.preventDefault(); }, false); 

the removeEventListener function does not seem to work. I did a little search on similar cases, and, unfortunately, I can not find a solution. I appreciate any help.

+4
source share
2 answers

You send an anonymous function to addEventListener. Instead, use a named function and send it removeEventListener, for example:

 function handleTouchMove(e) { e.preventDefault(); } document.addEventListener('touchmove', handleTouchMove, false); document.removeEventListener('touchmove', handleTouchMove); 

Otherwise, as you did, the function you sent removeEventListener was a completely different function, although it contained the same content.

+12
source

You must pass the actual link to this function as follows:

 function handleTouch(e) { e.preventDefault(); } document.addEventListener('touchmove', handleTouch, false); document.removeEventListener('touchmove', handleTouch, false); 

You cannot use a second copy of another anonymous function, even if it has the same code.

+2
source

Source: https://habr.com/ru/post/1393712/


All Articles