aBloomer aBloomer - 2 years ago 274
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");

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download