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 withaddEventListener.options→ (Optional) Must match the options used when adding (like{ once: true }orcapture: 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:
- 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 removeBecause those are two different function objects. - If you used an anonymous function, you can’t remove it later. Use a named function if you plan to remove it.
- The
options(likecapture: true) must match when removing.
