Register and remove event listeners
Quick answer
An EventTarget receives named events. Register a callback using addEventListener(type, callback, options). More than one listener can respond to the same event. Removal matches the event type, callback identity and capture flag; use the same function reference. An anonymous function newly created at removal time is a different object.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const b=document.createElement("button");let n=0;const hit=()=>n++;b.addEventListener("click",hit);b.addEventListener("click",hit);b.click();console.log(n);Expected console output:
1Duplicate registration does not add a second matching listener.
const b=document.createElement("button");let n=0;const hit=()=>n++;b.addEventListener("click",hit);b.click();b.removeEventListener("click",hit);b.click();console.log(n);Expected console output:
1Only the first click invokes the removed listener.
Common mistake
Pass the function, not the result of calling it. Re-registering the same callback with the same type and capture does not add a duplicate.
Practice
Create a button with two named click handlers, remove one and predict the result of another click.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Register and remove event listeners — Knowledge Check
Apply the concept and predict the browser example behavior.
Which value should be passed as the listener callback?
Which option must match when removing a registered listener?
Why can a newly written identical arrow function fail to remove a listener?
What is the exact console output in Register and remove event listeners example 1?
const b=document.createElement("button");let n=0;const hit=()=>n++;b.addEventListener("click",hit);b.addEventListener("click",hit);b.click();console.log(n);What is the exact console output in Register and remove event listeners example 2?
const b=document.createElement("button");let n=0;const hit=()=>n++;b.addEventListener("click",hit);b.click();b.removeEventListener("click",hit);b.click();console.log(n);