addEventListener
Registers a listener.
Event listeners connect events to functions. They can be added, removed and configured with options.
function handleClick() {
console.log("saved");
}
button.addEventListener("click", handleClick);
Events & Forms
addEventListener takes an event type, a callback and optional configuration. The same element can have multiple listeners for the same event.
Named functions are easier to remove than anonymous functions because removeEventListener needs the same function reference.
Options such as once, capture and passive change how the listener behaves. Use them deliberately, not by habit.
Registers a listener.
Removes a listener by matching the same callback.
Runs the listener only one time.
Promises not to call preventDefault.
Examples
function handleSave() {
saveDraft();
}
button.addEventListener("click", handleSave);
button.removeEventListener("click", handleSave);
button.addEventListener("click", () => saveDraft());
button.removeEventListener("click", () => saveDraft());
// These are two different functions.
Code patterns
These examples are the event patterns you will reuse constantly: listen, inspect, prevent, delegate, validate and submit.
Useful when you may remove it later.
function handleClick() {
console.log("clicked");
}
button.addEventListener("click", handleClick);
Use the same function reference.
button.removeEventListener("click", handleClick);
Good for one-time setup actions.
button.addEventListener("click", setup, { once: true });
Modern cleanup pattern for groups of listeners.
const controller = new AbortController();
button.addEventListener("click", save, { signal: controller.signal });
controller.abort();
Rules that matter
Events are user-facing code. Good handlers stay small, respect native behavior and keep visual, semantic and data state aligned.
The callback reference must match.
Repeated registration can fire the same logic many times.
One-time interactions do not need manual cleanup.
One abort can remove multiple listeners.
passive listeners cannot prevent default behavior.
A listener should respond to one event, not run an entire application.
Production thinking
Listener management prevents duplicate behavior, memory leaks and impossible-to-debug repeated actions.
Listeners should be attached to semantic controls so keyboard activation works without extra code.
Production interfaces should remove listeners when temporary UI is destroyed or no longer active.
Real links and forms should keep working without relying on fragile listener setup whenever possible.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain what fires, where it fires and what default behavior remains, you understand the interaction.