Chinchan Zu
Chinchan Zu

Reputation: 918

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.

Upvotes: 4

Views: 5726

Answers (2)

jfriend00
jfriend00

Reputation: 707148

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.

Upvotes: 2

Howard
Howard

Reputation: 3895

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.

Upvotes: 13

Related Questions