Events and addEventListener
An event is a signal that something happened on the page: a click, a key press, a form submission, the page finishing loading. An event listener (or handler) is a function you register to run when a particular event happens on a particular element. Events are how a page becomes interactive: almost every line of front-end JavaScript runs because some event triggered it. The standard way to listen is addEventListener.
In One Minute
element.addEventListener("click", handler)runshandlereach time the element is clicked.- The handler receives an event object with details:
event.type,event.target,event.key, coordinates and more. - Remove a listener with
removeEventListenerusing the same function reference, or with anAbortControllersignal. - Options:
{ once: true }runs it one time;{ signal }removes it on abort;{ passive: true }promises not to callpreventDefault. - Inline
onclick="..."attributes andelement.onclick = fnare older ways; preferaddEventListener.
addEventListener
Syntax
element.addEventListener(type, listener, options);| Argument | Meaning |
|---|---|
type | The event name, as a string: "click", "input", "submit", "keydown"... |
listener | The function to call; it receives the event object |
options | Optional: { once, passive, capture, signal } |
Example
<button id="pay" type="button">Record payment</button>
<p id="status">No payments yet</p>
<script>
let count = 0;
const status = document.querySelector("#status");
document.querySelector("#pay").addEventListener("click", () => {
count++;
status.textContent = `${count} payment(s) recorded`;
console.log(status.textContent);
});
</script>1 payment(s) recorded
2 payment(s) recordedThe checker clicked the button twice; each click ran the listener once. You can add many listeners to the same element and event: they all run, in the order they were added.
Common Event Types
| Category | Events |
|---|---|
| Mouse and pointer | click, dblclick, contextmenu, pointerdown, pointerup, pointermove, pointerenter, pointerleave |
| Keyboard | keydown, keyup |
| Focus | focus, blur, focusin, focusout |
| Form | input, change, submit, reset, invalid |
| Page | DOMContentLoaded, load, beforeunload, pagehide, visibilitychange |
| Window | resize, scroll, online, offline |
| Clipboard | copy, cut, paste |
| Animation | transitionend, animationend |
The Event Object
Every listener receives an event object describing what happened. The properties depend on the event type, but a few are on every event:
| Property or method | Meaning |
|---|---|
event.type | The event name, such as "click" |
event.target | The element where the event started (the exact thing clicked) |
event.currentTarget | The element whose listener is running now |
event.timeStamp | When it happened, in milliseconds since the page loaded |
event.preventDefault() | Stops the browser's default action (following a link, submitting a form) |
event.stopPropagation() | Stops the event from reaching ancestors (next lesson) |
event.isTrusted | true for real user actions, false for events created by scripts |
<button id="save" type="button">Save <strong>now</strong></button>
<script>
document.querySelector("#save").addEventListener("click", (event) => {
console.log(event.type);
console.log(event.target.tagName, event.currentTarget.tagName);
console.log(event.isTrusted);
});
</script>click
STRONG BUTTON
trueExplanation: the checker clicked the word "now", which is a <strong> inside the button. event.target is the innermost element clicked (STRONG); event.currentTarget is the element the listener is attached to (BUTTON). This distinction drives event delegation, covered in the next lesson.
Preventing Default Actions
Many events have a default action the browser performs after the listeners run: a link navigates, a form submits and reloads the page, a checkbox toggles. event.preventDefault() cancels it:
<a id="help" href="https://example.com/help">Help</a>
<script>
document.querySelector("#help").addEventListener("click", (event) => {
event.preventDefault();
console.log("Showing help in the page instead of navigating");
console.log(event.defaultPrevented);
});
</script>Showing help in the page instead of navigating
trueThe most common use is form submission: form.addEventListener("submit", (e) => { e.preventDefault(); ... }) lets JavaScript handle the data without reloading the page (see the forms lesson).
Removing Listeners
removeEventListener must receive the same function that was added. An inline arrow can't be removed, because a second identical-looking arrow is a different function:
<button id="b" type="button">Click</button>
<script>
const button = document.querySelector("#b");
let clicks = 0;
function onClick() {
clicks++;
console.log("click", clicks);
if (clicks === 2) button.removeEventListener("click", onClick);
}
button.addEventListener("click", onClick);
</script>click 1
click 2The third click did nothing: the named function onClick was removed after the second.
once and signal
Two options make removal easier:
<button id="welcome">Welcome</button>
<button id="track">Track</button>
<button id="stop">Stop tracking</button>
<script>
document.querySelector("#welcome").addEventListener("click", () => console.log("welcome shown"), { once: true });
const controller = new AbortController();
document.querySelector("#track").addEventListener("click", () => console.log("tracked"), { signal: controller.signal });
document.querySelector("#stop").addEventListener("click", () => controller.abort());
</script>welcome shown
tracked{ once: true } removes the listener after its first run. { signal } removes it when the AbortController is aborted; one controller can remove many listeners at once, which is ideal when a whole component is closed. (AbortController also cancels network requests; see the lesson on canceling and timeouts.)
The Older Ways
You'll still see two older styles:
<!-- 1. Inline attribute: JavaScript inside HTML (avoid) -->
<button onclick="pay()">Pay</button>
<script>
// 2. Event handler property: only ONE handler per event
const button = document.querySelector("button");
button.onclick = () => console.log("first");
button.onclick = () => console.log("second"); // replaces the first
</script>addEventListener | el.onclick = fn | onclick="..." attribute | |
|---|---|---|---|
| Several handlers per event | Yes | No (each assignment replaces) | No |
Options (once, signal, passive, capture) | Yes | No | No |
| Keeps JavaScript out of HTML | Yes | Yes | No |
| Allowed by a strict Content Security Policy | Yes | Yes | No |
Inline attributes also run code built from a string, which strict security policies block. Use addEventListener.
In Practice
The Fee Tracker's payment buttons record a payment, disable themselves to prevent double-clicks, and clean up all listeners when the "Close" button is used:
<button id="pay-navika" data-name="Navika" data-amount="120">Pay for Navika</button>
<button id="pay-advitha" data-name="Advitha" data-amount="45">Pay for Advitha</button>
<button id="close">Close</button>
<script>
const controller = new AbortController();
const { signal } = controller;
for (const button of document.querySelectorAll("[data-name]")) {
button.addEventListener("click", (event) => {
const { name, amount } = event.currentTarget.dataset;
event.currentTarget.disabled = true;
console.log(`Recorded $${amount} for ${name}`);
}, { signal });
}
document.querySelector("#close").addEventListener("click", () => {
controller.abort();
console.log("Payment buttons closed");
}, { once: true });
</script>Recorded $120 for Navika
Payment buttons closedThe second click on Navika's button did nothing because the button was disabled. After "Close", the listeners were removed, so clicking Advitha's button did nothing either.
Common Mistakes
Calling the handler instead of passing it. addEventListener("click", save()) runs save immediately. Pass save.
Removing an anonymous function. removeEventListener("click", () => ...) removes nothing. Keep a reference, or use once or signal.
Using event.target when you mean the element with the listener. Use event.currentTarget.
Writing event names with "on". addEventListener("onclick", ...) never fires. The name is "click".
Interview Corner
What is the difference between event.target and event.currentTarget?
target is the node where the event originated (the innermost element clicked). currentTarget is the element whose listener is currently executing, which differs from target when the event bubbles up from a descendant. currentTarget is only set during dispatch; it's null afterward.
Why prefer addEventListener over onclick?
It allows multiple listeners for the same event, supports options (once, passive, capture, signal), keeps behavior out of HTML, and works with Content Security Policy, which blocks inline handlers. Assigning onclick replaces any previous handler.
Practice
Challenge: Make a button that counts clicks and stops responding after 3, using the signal option instead of removeEventListener.
Show solution
<button id="b">Vote</button>
<script>
const controller = new AbortController();
let votes = 0;
document.querySelector("#b").addEventListener("click", () => {
votes++;
console.log("vote", votes);
if (votes === 3) controller.abort();
}, { signal: controller.signal });
</script>vote 1
vote 2
vote 3Key Takeaways
| Task | Code |
|---|---|
| Listen | el.addEventListener("click", handler) |
| One time | { once: true } |
| Remove later | { signal: controller.signal } then controller.abort() |
| Stop default | event.preventDefault() |
| Element with the listener | event.currentTarget |
Was this tutorial helpful?