0
0
JavascriptHow-ToBeginner · 3 min read

How to Remove Event Listener in JavaScript: Simple Guide

To remove an event listener in JavaScript, use removeEventListener with the same event type, function reference, and options as when you added it with addEventListener. This stops the function from running when the event happens.
📐

Syntax

The removeEventListener method requires three parts:

  • event type: a string like 'click' that names the event.
  • listener function: the exact function you want to stop listening.
  • options (optional): an object or boolean matching the one used when adding the listener.

All three must match exactly for the listener to be removed.

javascript
element.removeEventListener(eventType, listenerFunction, options);
💻

Example

This example shows adding a click event listener to a button, then removing it so clicking the button no longer triggers the alert.

javascript
const button = document.createElement('button');
button.textContent = 'Click me';
document.body.appendChild(button);

function showAlert() {
  alert('Button clicked!');
}

// Add event listener
button.addEventListener('click', showAlert);

// Remove event listener after 5 seconds
setTimeout(() => {
  button.removeEventListener('click', showAlert);
  console.log('Event listener removed');
}, 5000);
Output
Event listener removed
⚠️

Common Pitfalls

Common mistakes when removing event listeners include:

  • Using a different function reference than the one added. Anonymous functions cannot be removed because they are different objects.
  • Not matching the event type exactly (e.g., 'click' vs 'Click').
  • Omitting or mismatching the options parameter if it was used when adding the listener.

Always keep a reference to the original function and use the same parameters.

javascript
const btn = document.createElement('button');
btn.textContent = 'Test';
document.body.appendChild(btn);

// Wrong: anonymous function added
btn.addEventListener('click', () => alert('Hi'));

// Trying to remove with a different anonymous function - does NOT work
btn.removeEventListener('click', () => alert('Hi'));

// Correct way:
function greet() {
  alert('Hi');
}
btn.addEventListener('click', greet);
btn.removeEventListener('click', greet);
📊

Quick Reference

Remember these tips when removing event listeners:

  • Use the exact same function reference.
  • Match the event type string exactly.
  • Include the same options if used.
  • Store your listener functions in variables or named functions.

Key Takeaways

Use removeEventListener with the same event type and function reference to stop listening.
Anonymous functions cannot be removed; always use named or stored functions.
Match all parameters exactly, including options, to successfully remove listeners.
Keep references to your event handler functions for easy removal.
Removing event listeners helps prevent memory leaks and unwanted behavior.