Events & Event Listeners
Events are signals fired by the browser when something happens — a click,
a keypress, a page load. addEventListener() lets you
react to those signals with your own code.
Together they form the foundation of all interactive JavaScript —
from simple button clicks to complex drag-and-drop UIs.
addEventListener, removeEventListener, and inline handlers
event object — target, type,
preventDefault()
stopPropagation()
What Are Events?
Every time a user interacts with a webpage — or the browser itself does something — an event is fired. Think of events as notifications: the browser says "something just happened" and your JavaScript code can listen and respond. Events are the bridge between static HTML and dynamic, interactive applications.
addEventListener — The Right Way
There are three ways to attach an event handler, but
addEventListener() is the modern,
recommended
approach. It's non-destructive (multiple handlers on the same element), allows
removing listeners later, and supports the capture phase.
querySelector,
getElementById, or any DOM selector to get the element you want to
listen on.
"click"), your
callback function, and optional options like { once: true }.event object to your handler automatically.event object — you can inspect what was clicked, prevent defaults,
and more.
// ── Syntax ───────────────────────────────────────────────────
element.addEventListener(eventType, handler, options);
// ── 1. Basic click listener ───────────────────────────────────
const btn = document.querySelector("#myBtn");
btn.addEventListener("click", function() {
console.log("Button clicked!");
});
// ── 2. Arrow function handler ─────────────────────────────────
btn.addEventListener("click", () => {
console.log("Arrow function handler!");
});
// ── 3. Named function — best for removeEventListener ─────────
function handleClick() {
console.log("Named handler — can be removed!");
}
btn.addEventListener("click", handleClick);
// ── 4. Multiple listeners on the same element ─────────────────
btn.addEventListener("click", () => console.log("Handler A"));
btn.addEventListener("click", () => console.log("Handler B"));
// Both run! Order: A then B
// ── 5. { once: true } — fires exactly one time ───────────────
btn.addEventListener("click", () => {
console.log("This fires only once, then auto-removes");
}, { once: true });
// ── 6. removeEventListener ────────────────────────────────────
btn.removeEventListener("click", handleClick); // removes named handler
// ⚠️ You CANNOT remove an anonymous arrow function| Method | Multiple Handlers? | Removable? | Recommended? |
|---|---|---|---|
| addEventListener |
|
|
|
| onclick = fn |
|
|
|
| onclick="fn()" |
|
|
|
removeEventListener later (e.g. cleanup in SPAs). Anonymous arrow functions
cannot be removed because each reference is unique.
The Event Object
When an event fires, the browser automatically passes an event object to your handler. It contains rich information about what happened — which element was clicked, which key was pressed, the mouse position, and much more. You can also use it to control the event's default behaviour and propagation.
// ── Basic: receive the event object (named 'e' or 'event') ───
btn.addEventListener("click", (e) => {
console.log(e.type); // "click"
console.log(e.target); // the element that was clicked
console.log(e.currentTarget); // the element the listener is on
console.log(e.timeStamp); // ms since page load
});
// ── Mouse event properties ───────────────────────────────────
document.addEventListener("mousemove", (e) => {
console.log(e.clientX, e.clientY); // position relative to viewport
console.log(e.pageX, e.pageY); // position relative to document
console.log(e.button); // 0=left, 1=middle, 2=right
});
// ── Keyboard event properties ────────────────────────────────
document.addEventListener("keydown", (e) => {
console.log(e.key); // "Enter", "ArrowUp", "a", etc.
console.log(e.code); // "KeyA", "Enter", "Space"
console.log(e.ctrlKey); // true if Ctrl held
console.log(e.shiftKey); // true if Shift held
console.log(e.altKey); // true if Alt held
if (e.key === "Escape") closeModal(); // ESC to close
if (e.ctrlKey && e.key === "s") { e.preventDefault(); saveDoc(); }
});
// ── preventDefault — stop browser's default action ───────────
const link = document.querySelector("a");
link.addEventListener("click", (e) => {
e.preventDefault(); // don't follow the link
console.log("Link click intercepted!");
});
// ── stopPropagation — stop event from bubbling up ────────────
const inner = document.querySelector("#inner");
inner.addEventListener("click", (e) => {
e.stopPropagation(); // parent's click listener won't fire
console.log("Inner clicked — stopped here.");
});
// ── e.target vs e.currentTarget ──────────────────────────────
// currentTarget — always the element with the listener
// target — the element the user actually interacted with
const list = document.querySelector("ul");
list.addEventListener("click", (e) => {
console.log(e.target.tagName); // "LI" (what was clicked)
console.log(e.currentTarget.tagName); // "UL" (where listener lives)
});Event Propagation — Bubbling & Capturing
When an event fires on a nested element, it doesn't stay there — it travels through the DOM in three phases. Understanding this is critical for writing efficient event-driven code and avoiding mysterious double-firing bugs.
// ── Default: Bubble phase (3rd arg omitted or false) ─────────
// Click on #child → fires child, then parent, then document
document.querySelector("#parent").addEventListener("click", () => {
console.log("Parent clicked (bubble)");
});
document.querySelector("#child").addEventListener("click", () => {
console.log("Child clicked");
});
// Output when #child is clicked: "Child clicked" → "Parent clicked"
// ── Capture phase (3rd arg = true) ───────────────────────────
// Parent fires FIRST even though child was clicked
document.querySelector("#parent").addEventListener("click", () => {
console.log("Parent fires in CAPTURE phase");
}, true); // ← capture flag
// ── stopPropagation — stop bubbling at any point ─────────────
document.querySelector("#child").addEventListener("click", (e) => {
e.stopPropagation(); // parent listener will NOT fire
console.log("Stopped at child");
});
// ── stopImmediatePropagation — also stops OTHER handlers ─────
// on the SAME element
btn.addEventListener("click", (e) => {
e.stopImmediatePropagation(); // prevents next handler on btn too
console.log("First handler — blocks second");
});
btn.addEventListener("click", () => {
console.log("This NEVER runs");
});
// ── Most events bubble, some do not ──────────────────────────
// ✅ bubble: click, keydown, submit, input, change, mousemove
// ❌ no bubble: focus, blur, load, scroll (use focusin/focusout instead)false).
Capture phase (true) is only needed for rare advanced cases like intercepting
events
before they reach a child. If you're seeing double-fires, check for unintended bubbling first.
Common Event Patterns
Here are the most frequently used real-world patterns you'll encounter every day — from form handling to keyboard shortcuts.
// ── 1. Form submit — prevent reload, grab values ─────────────
const form = document.querySelector("#loginForm");
form.addEventListener("submit", (e) => {
e.preventDefault(); // stop page reload
const email = form.querySelector("[name=email]").value.trim();
const pass = form.querySelector("[name=password]").value;
if (!email) return alert("Email required");
login(email, pass);
});
// ── 2. Live search / debounce on input ───────────────────────
let timer;
document.querySelector("#searchBox").addEventListener("input", (e) => {
clearTimeout(timer);
timer = setTimeout(() => fetchResults(e.target.value), 400);
});
// ── 3. Keyboard shortcut (Ctrl+K to open search) ─────────────
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.key === "k") {
e.preventDefault();
openSearchModal();
}
});
// ── 4. Click outside to close modal ──────────────────────────
const modal = document.querySelector("#modal");
document.addEventListener("click", (e) => {
if (!modal.contains(e.target)) modal.classList.remove("open");
});
// ── 5. Once-only listener — e.g. play button ─────────────────
btn.addEventListener("click", startIntro, { once: true });
// ── 6. Passive listeners — better scroll performance ─────────
document.addEventListener("scroll", onScroll, { passive: true });
// { passive: true } tells browser: "I won't call preventDefault()"
// This lets the browser scroll without waiting for your JS
// ── 7. Toggle active class on nav items ──────────────────────
document.querySelectorAll(".nav-item").forEach(item => {
item.addEventListener("click", () => {
document.querySelectorAll(".nav-item").forEach(i => i.classList.remove("active"));
item.classList.add("active");
});
});
// ── 8. Clean up listener when no longer needed ───────────────
function onResize() { console.log("window width:", window.innerWidth); }
window.addEventListener("resize", onResize);
// Later, when component unmounts:
window.removeEventListener("resize", onResize);Event Delegation
Instead of attaching a listener to every child element, attach one listener
to a parent and use e.target to figure out
which child
was clicked. This is called event delegation — it's more performant,
and it automatically handles dynamically added elements.
// ── ❌ Without delegation — attaches 100 listeners ───────────
document.querySelectorAll(".todo-item").forEach(item => {
item.addEventListener("click", deleteTodo);
});
// Also breaks for dynamically added items!
// ── ✅ With delegation — ONE listener on the parent ──────────
const todoList = document.querySelector("#todoList");
todoList.addEventListener("click", (e) => {
// Check if the clicked element (or ancestor) is a .delete-btn
const deleteBtn = e.target.closest(".delete-btn");
const editBtn = e.target.closest(".edit-btn");
if (deleteBtn) {
deleteBtn.closest(".todo-item").remove();
} else if (editBtn) {
openEditModal(editBtn.dataset.id);
}
});
// ── Works for dynamically added items too! ───────────────────
function addTodo(text) {
todoList.insertAdjacentHTML("beforeend", `
<li class="todo-item">
<span>${text}</span>
<button class="delete-btn">Delete</button>
<button class="edit-btn" data-id="${Date.now()}">Edit</button>
</li>
\`); // the single listener above handles these automatically
}
// ── e.target.closest() — traverses UP the DOM ────────────────
// Returns the nearest ancestor (incl. self) matching the selector
// Returns null if not found — always check before using!
const item = e.target.closest(".todo-item");
if (item) { /* safe to use item */ }e.target.closest('.selector') instead of checking
e.target.classList directly. closest() handles clicks on
child elements inside your target (e.g. an icon inside a button) — making
your delegation robust and bug-free.
Try It — Live Editor
Experiment with JavaScript events directly below. Click, type, move the mouse, and watch the event log update in real time.
Common Pitfalls & Best Practices
A few gotchas that trip up beginners — and the clean patterns to use instead.
// ── ❌ Pitfall 1: Querying before DOM is ready ───────────────
const btn = document.querySelector("#btn"); // null if placed in <head>
btn.addEventListener("click", fn); // ❌ TypeError: null
// ✅ Wrap in DOMContentLoaded, or put script at bottom of <body>
document.addEventListener("DOMContentLoaded", () => {
const btn = document.querySelector("#btn");
btn.addEventListener("click", fn); // ✅ safe
});
// ── ❌ Pitfall 2: this inside arrow function ─────────────────
btn.addEventListener("click", () => {
console.log(this); // ❌ window (not the button)
});
// ✅ Use regular function or e.currentTarget
btn.addEventListener("click", function() {
console.log(this); // ✅ the button element
});
btn.addEventListener("click", (e) => {
console.log(e.currentTarget); // ✅ also the button
});
// ── ❌ Pitfall 3: memory leak — listener on removed element ──
function setupModal() {
const modal = document.querySelector("#modal");
document.addEventListener("keydown", closeOnEsc); // ← leaks if modal removed!
}
// ✅ Always clean up global listeners when element unmounts
function teardownModal() {
document.removeEventListener("keydown", closeOnEsc);
}
// ── ❌ Pitfall 4: calling handler immediately ────────────────
btn.addEventListener("click", doSomething()); // ❌ calls fn right now, passes return value
// ✅ Pass the reference, not the call
btn.addEventListener("click", doSomething); // ✅
btn.addEventListener("click", () => doSomething(arg)); // ✅ with args
// ── ✅ Best: use AbortController for multiple cleanup ─────────
const ac = new AbortController();
btn.addEventListener("click", fn1, { signal: ac.signal });
input.addEventListener("input", fn2, { signal: ac.signal });
// Remove all at once:
ac.abort(); // ✅ all listeners removed in one calldocument or window inside
component setup functions without a matching cleanup is the #1 cause of
memory leaks in JavaScript apps. Always pair your addEventListener
with a removeEventListener — or use the AbortController pattern
for bulk cleanup.
e.preventDefault() do?- Events are browser notifications fired when users interact with the page (click, type, scroll) or the browser does something (load, resize).
addEventListener(type, handler, options)is the recommended way to attach event listeners — it supports multiple handlers, removal, and the capture phase. Avoid inlineonclickHTML attributes andelement.onclick = fnpatterns.- The event object is automatically passed to your handler — it contains
target,currentTarget,type, mouse coordinates, key info, and control methods likepreventDefault()andstopPropagation(). - Event propagation has three phases: capture (down the DOM), target, and
bubble (up the DOM). By default, listeners fire in the bubble phase. Pass
trueas the third argument for capture. stopPropagation()prevents the event from travelling further up (or down) the DOM. Use it carefully — overuse hides bugs.- Event delegation — a single listener on a parent using
e.target.closest()— is more performant than many listeners on children, and works for dynamically added elements. - Always clean up listeners you add to
documentorwindow— useremoveEventListenerwith a named function,{ once: true }, or anAbortControllerfor bulk removal. - Use
{ passive: true }for scroll and touch listeners to improve page performance — it signals to the browser that you won't callpreventDefault().
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.