JavaScript Events: addEventListener, Bubbling and Event Delegation
A web page is idle until something happens: a click, a key press, a form submit or a page load. These are events, and JavaScript reacts to them with event listeners. Understanding events explains a lot of automation behaviour: why a value set by a script may not register in an app, why a click on an icon reaches its button, and why Playwright fires real, trusted input events. In this lesson you will add and remove listeners, read the event object, prevent default browser actions, follow events as they bubble up the page, use event delegation for dynamic lists, and create custom events. In the examples, a real Chrome browser performs the clicks and typing (the same way Playwright does), and you see what the listeners logged.
📖 What You’ll Learn: what events and listeners are, addEventListener and removeEventListener, the once option, the event object (type, target, currentTarget), common mouse, keyboard, form and page events, input vs change, preventDefault, bubbling and capturing, stopPropagation, event delegation with closest(), custom events with dispatchEvent, isTrusted, and debouncing input.
👂 Events and Listeners
Definition: an event is a signal that something happened in the page. An event listener (or handler) is a function you register with element.addEventListener(type, handler); the browser calls it every time that event happens on that element.
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="save">Save</button>
<p id="status">Not saved</p>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const button = document.querySelector("#save");
const status = document.querySelector("#status");
let clicks = 0;
button.addEventListener("click", () => {
clicks++;
status.textContent = `Saved ${clicks} time(s)`;
console.log(status.textContent);
});
console.log("listener added, waiting for clicks...");
🖥️ Browser console (after two clicks on Save)
listener added, waiting for clicks...
Saved 1 time(s)
Saved 2 time(s)
- Pass the function itself (
handler), not a call (handler()); otherwise it runs immediately. - One element can have many listeners for the same event; they run in the order they were added.
- Avoid inline HTML handlers such as
onclick="save()"and the single-slotel.onclick = fnproperty in new code;addEventListeneris more flexible.
📨 The Event Object
The browser passes an event object to your handler with details about what happened:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="buy" data-sku="KB-01">Buy <span class="icon">🛒</span></button>
<input id="search" placeholder="Search">
<script src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#buy").addEventListener("click", (event) => {
console.log("type:", event.type);
console.log("target:", event.target); // what was actually clicked
console.log("currentTarget:", event.currentTarget); // the element the listener is on
console.log("sku:", event.currentTarget.dataset.sku);
console.log("trusted:", event.isTrusted);
});
document.querySelector("#search").addEventListener("keydown", (event) => {
console.log("key:", event.key, "| code:", event.code, "| ctrl:", event.ctrlKey);
});
🖥️ Browser console (after clicking the cart icon, then pressing Enter and Ctrl+K in the search box)
type: click
target: <span class="icon">
currentTarget: <button id="buy" data-sku="KB-01">
sku: KB-01
trusted: true
key: Enter | code: Enter | ctrl: false
key: Control | code: ControlLeft | ctrl: true
key: k | code: KeyK | ctrl: true
event.target is the innermost element that was clicked (here the icon span), while event.currentTarget is the element you attached the listener to (the button). This difference is the key to event delegation, below.
| Property / method | Meaning |
|---|---|
type | The event name, such as “click” |
target | The element where the event started |
currentTarget | The element whose listener is running |
key / code | Keyboard: the character (“Enter”, “a”) / the physical key (“KeyA”) |
clientX, clientY | Mouse position in the viewport |
isTrusted | true if generated by the browser from real user input |
preventDefault() | Cancel the browser’s default action |
stopPropagation() | Stop the event from bubbling further |
📋 Common Events
| Category | Events |
|---|---|
| Mouse | click, dblclick, contextmenu, mousedown/mouseup, mouseover/mouseout, mouseenter/mouseleave |
| Pointer and touch | pointerdown, pointerup, pointermove (mouse, pen and touch together) |
| Keyboard | keydown, keyup |
| Form | input, change, submit, focus, blur, focusin/focusout |
| Page | DOMContentLoaded, load, beforeunload, visibilitychange, scroll, resize |
| Clipboard and drag | copy, paste, dragstart, drop |
input vs change
input fires on every keystroke; change fires when the user commits the value, which for a text field means leaving it (blur) after editing:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="name" placeholder="Name">
<select id="size"><option>S</option><option>M</option><option>L</option></select>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const name = document.querySelector("#name");
name.addEventListener("input", () => console.log("input:", name.value));
name.addEventListener("change", () => console.log("change:", name.value));
const size = document.querySelector("#size");
size.addEventListener("change", () => console.log("size changed to", size.value));
🖥️ Browser console (after typing “Ana”, clicking elsewhere and choosing L)
input: A
input: An
input: Ana
change: Ana
size changed to L
💡 Tip: This is why setting input.value = "x" from a script often “does not work” in React or Angular apps: no input event fires, so the framework never sees the new value. Playwright’s fill() and pressSequentially() fire the real events.
🚫 preventDefault, once and removeEventListener
Some events have a default action: a link navigates, a form submits and reloads the page, a checkbox toggles. event.preventDefault() cancels it so your code can handle things instead:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<a id="docs" href="/docs">Docs</a>
<form id="login"><input name="email" value="qa@sqatools.in"><button>Log in</button></form>
<script src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#docs").addEventListener("click", (e) => {
e.preventDefault(); // stay on this page
console.log("navigation blocked, would go to", e.currentTarget.getAttribute("href"));
});
document.querySelector("#login").addEventListener("submit", (e) => {
e.preventDefault(); // no page reload
const email = new FormData(e.currentTarget).get("email");
console.log("submitting via JavaScript for", email);
});
🖥️ Browser console (after clicking the link and the Log in button)
navigation blocked, would go to /docs
submitting via JavaScript for qa@sqatools.in
Listeners can be removed with removeEventListener, which needs the same function reference, so use a named function. The { once: true } option removes the listener automatically after the first call:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="go">Go</button>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const go = document.querySelector("#go");
function logClick() { console.log("named listener"); }
go.addEventListener("click", logClick);
go.addEventListener("click", () => console.log("once listener"), { once: true });
go.addEventListener("click", () => {
go.removeEventListener("click", logClick); // remove after the first click
console.log("--- click handled ---");
});
🖥️ Browser console (after two clicks)
named listener
once listener
--- click handled ---
--- click handled ---
🫧 Bubbling and Capturing
When you click an element, the event does not stay there. It travels down from window to the target (capturing phase), then back up through every ancestor (bubbling phase). Listeners run during bubbling by default; pass { capture: true } to run during capturing:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="card">
<div id="footer">
<button id="like">Like</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const log = (name) => (e) => console.log(`${name} (phase ${e.eventPhase})`);
document.querySelector("#card").addEventListener("click", log("card capture"), { capture: true });
document.querySelector("#card").addEventListener("click", log("card bubble"));
document.querySelector("#footer").addEventListener("click", log("footer bubble"));
document.querySelector("#like").addEventListener("click", log("button target"));
document.body.addEventListener("click", log("body bubble"));
🖥️ Browser console (after clicking Like)
card capture (phase 1)
button target (phase 2)
footer bubble (phase 3)
card bubble (phase 3)
body bubble (phase 3)
Phases: 1 = capturing, 2 = at the target, 3 = bubbling. event.stopPropagation() stops the journey, for example so that clicking “Like” inside a clickable card does not also open the card:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="card">Product card
<button id="like">Like</button>
</div>
<script src="app.js"></script>
</body>
</html>
📄 app.js
document.querySelector("#card").addEventListener("click", () => console.log("open product page"));
document.querySelector("#like").addEventListener("click", (e) => {
e.stopPropagation();
console.log("liked (card not opened)");
});
🖥️ Browser console (after clicking Like, then the card itself)
liked (card not opened)
open product page
⚠️ Watch out: Use stopPropagation() sparingly. Analytics, modals that close on outside clicks and event delegation all rely on events bubbling up; stopping them can create hard-to-find bugs.
🎯 Event Delegation
Because events bubble, one listener on a parent can handle clicks for all of its children, including children added later. This is event delegation. Use event.target.closest() to find which child was clicked:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<ul id="todos">
<li data-id="1">Write test plan <button class="delete">✕</button></li>
<li data-id="2">Run smoke tests <button class="delete">✕</button></li>
</ul>
<button id="add">Add item</button>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const todos = document.querySelector("#todos");
// ONE listener for every current and future delete button
todos.addEventListener("click", (e) => {
const button = e.target.closest(".delete");
if (!button) return; // the click was not on a delete button
const item = button.closest("li");
console.log("deleting item", item.dataset.id);
item.remove();
console.log("left:", todos.children.length);
});
let nextId = 3;
document.querySelector("#add").addEventListener("click", () => {
todos.insertAdjacentHTML("beforeend", `<li data-id="${nextId++}">New task <button class="delete">✕</button></li>`);
console.log("added, now", todos.children.length);
});
🖥️ Browser console (after adding an item, then deleting items 3 and 1)
added, now 3
deleting item 3
left: 2
deleting item 1
left: 1
- Fewer listeners: one per list instead of one per row.
- Works for elements created later (rows loaded from an API, infinite scroll).
- Always guard with
closest()and an earlyreturn, because the click may land on any child.
📣 Custom Events and isTrusted
You can create and dispatch your own events with CustomEvent, passing data in detail. Components use this to tell the rest of the page that something happened:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<div id="cart">Cart: 0</div>
<button id="add">Add to cart</button>
<script src="app.js"></script>
</body>
</html>
📄 app.js
const cart = document.querySelector("#cart");
let count = 0;
document.addEventListener("cart:updated", (e) => {
console.log(`cart:updated -> ${e.detail.count} item(s), last: ${e.detail.product}`);
});
document.querySelector("#add").addEventListener("click", (e) => {
count++;
cart.textContent = `Cart: ${count}`;
cart.dispatchEvent(new CustomEvent("cart:updated", { bubbles: true, detail: { count, product: "Mouse" } }));
console.log("click isTrusted:", e.isTrusted);
});
document.querySelector("#add").click(); // a click triggered by script
🖥️ Browser console (one click from code, then one real click)
cart:updated -> 1 item(s), last: Mouse
click isTrusted: false
cart:updated -> 2 item(s), last: Mouse
click isTrusted: true
Events created by scripts (el.click(), dispatchEvent) have isTrusted: false; events produced by the browser from real input have isTrusted: true. Some sites ignore untrusted events (for example for file pickers or full-screen requests). That is one reason Playwright drives the browser through its input pipeline instead of calling el.click(): its clicks are trusted, like a user’s.
🧪 Tester Scenario: Debounced Search
Search boxes often wait until the user stops typing before calling the API. This is called debouncing. Knowing it explains why a test must wait for results instead of checking right after typing:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="q" placeholder="Search products">
<ul id="results"></ul>
<script src="app.js"></script>
</body>
</html>
📄 app.js
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const products = ["USB Cable", "USB Hub", "Mouse", "Keyboard"];
let apiCalls = 0;
const search = debounce((term) => {
apiCalls++;
const hits = products.filter((p) => p.toLowerCase().includes(term.toLowerCase()));
document.querySelector("#results").innerHTML = hits.map((h) => `<li>${h}</li>`).join("");
console.log(`search #${apiCalls} for "${term}" -> ${hits.length} result(s)`);
}, 300);
document.querySelector("#q").addEventListener("input", (e) => {
console.log("typed:", e.target.value);
search(e.target.value);
});
🖥️ Browser console (after typing “usb” quickly)
typed: u
typed: us
typed: usb
search #1 for "usb" -> 2 result(s)
Three keystrokes produced only one search. A test that types and then immediately counts results would see an empty list. Playwright’s web-first assertions (await expect(page.locator("#results li")).toHaveCount(2)) retry until the debounced update has happened.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Log “Hello!” when a button with id greet is clicked.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="greet">Greet</button>
<script src="app.js"></script>
</body>
</html>📄 app.js
document.querySelector("#greet").addEventListener("click", () => console.log("Hello!"));🖥️ Browser console
Hello!Q2. Show a live character count under a textarea as the user types.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<textarea id="bio" maxlength="50"></textarea>
<p id="count">0/50</p>
<script src="app.js"></script>
</body>
</html>📄 app.js
const bio = document.querySelector("#bio");
const count = document.querySelector("#count");
bio.addEventListener("input", () => {
count.textContent = `${bio.value.length}/50`;
});
bio.addEventListener("change", () => console.log(count.textContent));🖥️ Browser console
11/50Q3. Log which key was pressed in an input, and clear the input when Escape is pressed.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<input id="field" value="draft text">
<script src="app.js"></script>
</body>
</html>📄 app.js
const field = document.querySelector("#field");
field.addEventListener("keydown", (e) => {
console.log("key:", e.key);
if (e.key === "Escape") {
field.value = "";
console.log("cleared, value is now:", JSON.stringify(field.value));
}
});🖥️ Browser console
key: a
key: Escape
cleared, value is now: ""Q4. Use ONE listener on #menu to log the text of whichever menu item is clicked.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<nav id="menu"><a href="#home">Home</a> <a href="#courses">Courses</a> <a href="#contact">Contact</a></nav>
<script src="app.js"></script>
</body>
</html>📄 app.js
document.querySelector("#menu").addEventListener("click", (e) => {
const link = e.target.closest("a");
if (!link) return;
e.preventDefault();
console.log("clicked:", link.textContent);
});🖥️ Browser console
clicked: Courses
clicked: ContactQ5. Make a “Subscribe” button that only works the first time it is clicked.
Show answer
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="sub">Subscribe</button>
<script src="app.js"></script>
</body>
</html>📄 app.js
document.querySelector("#sub").addEventListener("click", (e) => {
e.currentTarget.textContent = "Subscribed";
console.log("subscribed!");
}, { once: true });🖥️ Browser console
subscribed!Q6. Why does this code log “clicked” immediately when the page loads, and never on click? Fix it.
function handle() { console.log("clicked"); }
button.addEventListener("click", handle());Show answer
handle() calls the function right away and passes its return value (undefined) as the listener. Pass the function itself:
📄 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<button id="b">Click</button>
<script src="app.js"></script>
</body>
</html>📄 app.js
function handle() { console.log("clicked"); }
const button = document.querySelector("#b");
button.addEventListener("click", handle); // no parentheses
console.log("page loaded");🖥️ Browser console
page loaded
clicked🧠 MCQ Quiz: Events and Delegation
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which method registers an event listener?Answer: addEventListener. attachEvent was an old Internet Explorer method.
- What is
event.target?Answer: The element where the event started. currentTarget is the element with the listener. - Which event fires on every keystroke in a text input?Answer: input. change fires when the value is committed.
- What does
event.preventDefault()do on a form submit?Answer: Stops the browser’s default submit and page reload. Then JavaScript can send the data itself. - In which order do bubbling listeners run when a button inside a div is clicked?Answer: Button first, then div, then body. Bubbling goes from the target up.
- What is event delegation?Answer: One listener on a parent handles events from many children. It works because events bubble.
- What do you need to remove a listener with removeEventListener?Answer: The same function reference that was added. Anonymous functions cannot be removed this way.
- What does
{ once: true }do?Answer: Removes the listener automatically after it runs once. Handy for one-time actions. - What is
isTrustedfor an event fired byel.click()from a script?Answer: false. Only real user input produces trusted events. - Why might setting
input.valueby script not update a React app?Answer: No input event fires, so the framework does not see the change. Real typing (or Playwright fill) fires the events.
💼 Interview Questions and Answers
Q1. Explain event bubbling and event delegation.
After an event reaches its target, it bubbles up through every ancestor to document and window, so ancestors’ listeners also run. Event delegation uses this: instead of one listener per child, put one on a common parent and use event.target.closest(selector) to find which child was involved. It needs fewer listeners and automatically covers elements added later.
Q2. What is the difference between target and currentTarget?
target is the deepest element where the event originated, for example an icon inside a button. currentTarget is the element whose listener is currently running, the one you called addEventListener on. With delegation they are usually different; in a listener on the element itself they can be the same.
Q3. Why can a test that sets an input’s value directly fail where a real user succeeds?
Frameworks such as React, Vue and Angular update their state from input/change events. Assigning element.value changes the DOM but fires no event, so the app’s state still has the old value and validation or submit behaves differently. Use tools that simulate real input (Playwright fill/type), or dispatch the proper events when scripting manually.
Q4. What is debouncing and why does it matter for test stability?
Debouncing delays a function until events have stopped for a set time, for example only searching 300 ms after the last keystroke. Tests that check results immediately after typing become flaky because the update has not happened yet. Use auto-waiting assertions or wait for the network request that the debounced function triggers, never a fixed sleep.
❓ Frequently Asked Questions
🤔 Should I use onclick or addEventListener?
addEventListener. It allows several listeners per event, options such as once and capture, and keeps JavaScript out of the HTML.
🤔 Why does my listener not fire on elements added later?
Listeners are attached to the elements that existed when the code ran. Use event delegation on a parent that exists from the start.
🤔 What is the difference between mouseover and mouseenter?
mouseover bubbles and fires again when moving between child elements; mouseenter does not bubble and fires once when entering the element itself.
🤔 How do I trigger an event from code?
For a simple click call element.click(). For others create and dispatch an event: el.dispatchEvent(new Event("input", { bubbles: true })). These events have isTrusted set to false.
🏁 Summary
- Register handlers with
addEventListener(type, fn, options); remove them with the same function reference or use{ once: true }. - The event object gives
type,target,currentTarget, key and mouse details, pluspreventDefault()andstopPropagation(). inputfires per keystroke,changeon commit,submiton form submit (cancel it with preventDefault).- Events capture down and bubble up; delegation puts one listener on a parent and uses
closest(). - Script events are untrusted; real input is trusted. Debounced UIs need waiting assertions, not fixed sleeps.
Next, continue with Lesson 59: Forms and Validation.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in