Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add and remove an event listener using a function with parameters?

Sorry if this is a common question, but I couldn't find any answers that seemed pertinent through searching.

If I attach an event listener like this:

window.addEventListener('scroll', function() { check_pos(box); }, false); 

it doesn't seem to work to try to remove it later, like this:

window.removeEventListener('scroll', function() { check_pos(box); }, false); 

I assume this is because the addEventListener and removeEventListener methods want a reference to the same function, while I've provided them with anonymous functions, which, while identical in code, are not literally the same.

How can I change my code to get the call to removeEventListener to work? The "box" argument refers to the name of an <iframe> that I'm tracking on the screen; that is, I want to be able to subscribe to the scroll event once for each <iframe> that I have (the quantity varies), and once the check_pos() function measures a certain position, it will call another function and also remove the event listener to free up system resources.

My hunch is that the solution will involve a closure and/or naming the anonymous function, but I'm not sure exactly what that looks like, and would appreciate a concrete example.

Hope that makes sense.

like image 317
Bungle Avatar asked Jun 07 '10 16:06

Bungle


People also ask

Can you add an event listener in a function?

You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

How do I remove an event listener?

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.


2 Answers

Have you tried maintaining a reference to the anonymous function (like you suggested)?

So:

var listener = function() {   check_pos(box); };  window.addEventListener('scroll', listener, false); ... window.removeEventListener('scroll', listener, false); 

Mozilla's docs suggest the same thing.

like image 106
Vivin Paliath Avatar answered Sep 20 '22 09:09

Vivin Paliath


var listener;  listener = function(){  if( window.target != anotherEvent.target ) {     ...CODE where      window.removeEventListener('click', listener , false);  };  window.addEventListener('click', listener ,false); 
like image 40
Rodrigo Avatar answered Sep 19 '22 09:09

Rodrigo