Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing javascript eventlisteners

I have this following javascript to activate sometime

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

but I am having troubles removing the event listener when some i do this

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

the function removeEventListener doesnt seem to work. I did a little search on similar cases and unfortunately i cant find the solution. I appreciate any help.

like image 833
Chinchan Zu Avatar asked Dec 06 '22 16:12

Chinchan Zu


2 Answers

You are sending an anonymous function to the addEventListener call. Use a named function instead and send that to removeEventListener, like this:

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

document.removeEventListener('touchmove', handleTouchMove);

Otherwise, the way you were doing it, the function you sent to removeEventListener was a completely different function, even though it had the same contents.

like image 187
Howard Avatar answered Dec 22 '22 14:12

Howard


You have to pass the actual same function reference like this:

function handleTouch(e) {
    e.preventDefault();
}

document.addEventListener('touchmove', handleTouch, false);

document.removeEventListener('touchmove', handleTouch, false);

You can't use a second copy of a different anonymous function even if they have the same code in them.

like image 22
jfriend00 Avatar answered Dec 22 '22 14:12

jfriend00