How to remove an event handler in JavaScript

To remove an event handler that has been attached to an HTML element by using the addEventListener() method, you can use the removeEventListener() method.

The removeEventListener() takes in the name of the event (like click, change, etc.) and a reference to the event handler method as input, and remove it from the HTML DOM.

Let us say you have the following <button> element:

<button id="register">Register Now</button>

Now define a function that acts as an event handler:

const handler = (e) => {
    console.log(`Button is clicked!`);
};

The following code snippet attaches the above event handler to the click event of the button:

const btn = document.querySelector('#register');
btn.addEventListener('click', handler);

Now to remove the click event handler from the click event of the button, just use the removeEventListener() event handler as follows:

btn.removeEventListener('click', handler);

Note that the event name and the event handler function must be the same for removeEventListener() to work.

If you use an anonymous function as an event handler, you can not remove it. The following example won't work:

const btn = document.querySelector('#register');

// Attach an event handler
btn.addEventListener('click', (e) => {
    console.log(`Button is clicked!`);
});

// Remove an event handler
// It won't have any effect
btn.removeEventListener('click', (e) => {
    console.log(`Event is removed.`);
});

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.