# How to remove an event handler in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 29, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-remove-an-event-handler

> Learn how to remove an already attached event handler from an HTML element in JavaScript.

To remove an event handler that has been [attached](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) 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:

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

Now define a function that acts as an event handler:

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

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

```javascript
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:

```javascript
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:

```javascript
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.`);
});
```
