How to Remove Event Listeners in Javascript

javascript
Published on December 14, 2020

Events can be removed in Javascript using the removeEventListener() method.

function handlerFunc() {
	let x = 10;
	let y = 20;
}

document.querySelector("#element").addEventListener('click', handlerFunc);

document.querySelector("#element").removeEventListener('click', handlerFunc);

There are however a few things to note in order to remove the event successfully.

  • The callback function that is passed as parameter to removeEventListener() should be the same as that was passed to addEventListener() while adding the event.

    However the callback cannot be an anonymous function. It is not possible to get an exact match for two anonymous function even though they contain the same code.

    document.querySelector("#element").addEventListener('click', function() {
    	let x = 10;
    	let y = 20;
    });
    
    // won't work even though code in both callbacks are same
    document.querySelector("#element").removeEventListener('click', function() {
    	let x = 10;
    	let y = 20;
    });
    

    The solution is to use a normal function reference as callback to addEventListener(), and then use the same reference for removeEventListener().

    // event handler
    function handlerFunc() {
    	let x = 10;
    	let y = 20;	
    }
    
    document.querySelector("#element").addEventListener('click', handlerFunc);
    
    // works as both callback functions are same
    document.querySelector("#element").removeEventListener('click', handlerFunc);
    
  • If useCapture option was earlier passed to addEventListener(), then the same value should be passed to removeEventListener() as well. If both values don't match, event will not be removed.

    // event handler
    function handlerFunc() {
    	let x = 10;
    	let y = 20;	
    }
    
    document.querySelector("#element").addEventListener('click', handlerFunc, true);
    
    // important to set the same value of the third "useCapture" parameter
    document.querySelector("#element").removeEventListener('click', handlerFunc, true);
    
  • If it is required to remove the event after running only once, then there is no need to use removeEventListener().

    It will be enough to use addEventListener() with the once option set to true. This will automatically remove the event after executing once.

    // will execute only once
    document.querySelector("#element").addEventListener('click', function() {
    	let x = 10;
    	let y = 20;;
    }, { once: true });
    
In this Tutorial