[javascript] JavaScript: remove event listener

I'm trying to remove an event listener inside of a listener definition:

canvas.addEventListener('click', function(event) {
    click++;
    if(click == 50) {
        // remove this event listener here!
    }
// More code here ...

How could I do that? this = event... Thank you.

This question is related to javascript events event-handling listener

The answer is


If someone uses jquery, he can do it like this :

var click_count = 0;
$( "canvas" ).bind( "click", function( event ) {
    //do whatever you want
    click_count++;
    if ( click_count == 50 ) {
        //remove the event
        $( this ).unbind( event );
    }
});

Hope that it can help someone. Note that the answer given by @user113716 work nicely :)


I think you may need to define the handler function ahead of time, like so:

var myHandler = function(event) {
    click++; 
    if(click == 50) { 
        this.removeEventListener('click', myHandler);
    } 
}
canvas.addEventListener('click', myHandler);

This will allow you to remove the handler by name from within itself.


If @Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.

clickHandler = function(event){
  if (click++ == 49)
    canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);

You could use a named function expression (in this case the function is named abc), like so:

let click = 0;
canvas.addEventListener('click', function abc(event) {
    click++;
    if (click >= 50) {
        // remove event listener function `abc`
        canvas.removeEventListener('click', abc);
    }
    // More code here ...
}

Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.

More information about named function expressions: http://kangax.github.io/nfe/.


   canvas.addEventListener('click', function(event) {
      click++;
      if(click == 50) {
          this.removeEventListener('click',arguments.callee,false);
      }

Should do it.


You need to use named functions.

Also, the click variable needs to be outside the handler to increment.

var click_count = 0;

function myClick(event) {
    click_count++;
    if(click_count == 50) {
       // to remove
       canvas.removeEventListener('click', myClick);
    }
}

// to add
canvas.addEventListener('click', myClick);

EDIT: You could close around the click_counter variable like this:

var myClick = (function( click_count ) {
    var handler = function(event) {
        click_count++;
        if(click_count == 50) {
           // to remove
           canvas.removeEventListener('click', handler);
        }
    };
    return handler;
})( 0 );

// to add
canvas.addEventListener('click', myClick);

This way you can increment the counter across several elements.


If you don't want that, and want each one to have its own counter, then do this:

var myClick = function( click_count ) {
    var handler = function(event) {
        click_count++;
        if(click_count == 50) {
           // to remove
           canvas.removeEventListener('click', handler);
        }
    };
    return handler;
};

// to add
canvas.addEventListener('click', myClick( 0 ));

EDIT: I had forgotten to name the handler being returned in the last two versions. Fixed.


Try this, it worked for me.

<button id="btn">Click</button>
<script>
 console.log(btn)
 let f;
 btn.addEventListener('click', f=function(event) {
 console.log('Click')
 console.log(f)
 this.removeEventListener('click',f)
 console.log('Event removed')
})  
</script>

element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();


HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
    this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};


HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
    for (var i = 0; i < this.myListeners.length; i++) {
        this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
    };
   delete this.myListeners;
};
};

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?

Examples related to listener

Android - How to achieve setOnClickListener in Kotlin? Oracle client ORA-12541: TNS:no listener How to properly stop the Thread in Java? Can I have onScrollListener for a ScrollView? Create a custom event in Java TNS-12505: TNS:listener does not currently know of SID given in connect descriptor Remove an onclick listener Using Switch Statement to Handle Button Clicks JavaScript: remove event listener Counting Chars in EditText Changed Listener