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
}
}
window.removeEventListener("beforeunload",functionToRun);
var button=document.getElementById('button');
button.addEventListener('click',function(e){
//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) {
alert('clicked');
this.removeEventListener('click', arguments.callee);
});
<button id="button">click</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With