aBloomer aBloomer - 8 months ago 111
Javascript Question

How to remove event listener?

Below is my code for event listener

window.addEventListener("beforeunload", function (e) {
if(sessionStorage.token != "abide" ) {
// call api

What if I want to remove this event listener, what should I do?

Is the code working like below??

window.removeEventListener("before unload");


To remove event listener, your event handler function has to be an external named function, not anonymous (you need a reference to that function):

window.addEventListener("beforeunload", functionToRun);

function functionToRun (e) {
        if(sessionStorage.token != "abide" )  {
          // call api

Alternative : You can also remove it inside the anonymous function call using arguments.callee which is referencing that anonymous function.

var button=document.getElementById('button');


  //some code to be runned 

 this.removeEventListener('click', arguments.callee);

Note: your event handler function has to be fired once, in order to remove it in the above way.

var button = document.getElementById('button');

button.addEventListener('click', function(e) {


  this.removeEventListener('click', arguments.callee);
<button id="button">click</button>