HomeJAVASCRIPTHow do you remove an event listener?

How do you remove an event listener?

You can remove an event listener in JavaScript using removeEventListener.

Syntax:

element.removeEventListener(event, handler, options);
  • event → The event type (e.g., "click", "keydown").
  • handler → The exact function reference that was added with addEventListener.
  • options → (Optional) Must match the options used when adding (like { once: true } or capture: true).

Example:

function handleClick() {
  console.log("Button clicked!");
}

const btn = document.querySelector("#myBtn");

// Add event listener
btn.addEventListener("click", handleClick);

// Remove event listener
btn.removeEventListener("click", handleClick);

⚠️ Important Notes:

  1. You must pass the same function reference.
    This won’t work: btn.addEventListener("click", () => console.log("Clicked")); btn.removeEventListener("click", () => console.log("Clicked")); // ❌ won't remove Because those are two different function objects.
  2. If you used an anonymous function, you can’t remove it later. Use a named function if you plan to remove it.
  3. The options (like capture: true) must match when removing.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *