JavaScript Events – Event Bubbling, Capturing and Delegation
Imagine a school website with 1,000 student registrations. Each student has a separate action button. How should we handle all those clicks? Adding one listener to every button works. However, managing those listeners becomes harder as the page grows.
Let's use a school event registration page throughout this article. We will follow one student's click from start to finish.
1. What Is a JavaScript Event?
Event = an action that happens in the browser.
A click, key press, form submission or page load can create an event. JavaScript can listen for these actions and run a function.
Event listener = a function that waits for a browser event.
Example: Listen for a registration button click
const registerButton = document.querySelector("#registerButton");
registerButton.addEventListener("click", () => {
console.log("Registration button clicked");
});
Registration button clicked
addEventListener() connects an event with a function. The browser calls that function when the event happens.
2. The Problem: Handling Every Student Button Separately
Suppose the school website displays three student registrations. Each row has a button to view its registration details.
We can attach a separate listener to every button. This works for a small list.
<ul id="studentList">
<li>Priya
<button class="view-button" data-student="Priya">View</button>
</li>
<li>Ravi
<button class="view-button" data-student="Ravi">View</button>
</li>
<li>Lakshmi
<button class="view-button" data-student="Lakshmi">View</button>
</li>
</ul>
const buttons = document.querySelectorAll(".view-button");
buttons.forEach((button) => {
button.addEventListener("click", (event) => {
console.log(
"Viewing registration for:",
event.currentTarget.dataset.student
);
});
});
Viewing registration for: Priya Viewing registration for: Ravi Viewing registration for: Lakshmi
This works, but it gets harder to manage when the list grows.
What goes wrong when the list grows?
- We create many separate event listeners.
- New buttons need their own listeners.
- Removing or replacing elements needs extra care.
- Listener setup becomes harder to maintain.
- Large lists make repeated setup unnecessary.
Now think about 1,000 student registrations. We can handle these clicks through one parent listener instead.
3. Understand the Event Propagation Flow
Event propagation = the route an event follows through the DOM.
DOM = the browser's tree-like structure of page elements.
When you click a button, the event can travel through three phases:
- Capturing: The event travels from the outer page towards the clicked element.
- Target: The event reaches the element that was clicked.
- Bubbling: The event travels back through its parent elements.
Let's follow a click on Priya's registration button.
The event travels down during capturing, reaches the target, then travels upward during bubbling.
4. Event Capturing in JavaScript
Event capturing = the event travels from an ancestor towards the target.
We can listen during this phase by passing true as the third argument to addEventListener(). We can also pass an options object with capture: true.
Example: Capture the student's button click
<div id="schoolPage">
<ul id="studentList">
<li>
<button id="priyaButton">View Priya</button>
</li>
</ul>
</div>
const schoolPage = document.querySelector("#schoolPage");
const studentList = document.querySelector("#studentList");
const priyaButton = document.querySelector("#priyaButton");
schoolPage.addEventListener("click", () => {
console.log("1. School page - capturing");
}, true);
studentList.addEventListener("click", () => {
console.log("2. Student list - capturing");
}, true);
priyaButton.addEventListener("click", () => {
console.log("3. Priya button - target");
});
studentList.addEventListener("click", () => {
console.log("4. Student list - bubbling");
});
schoolPage.addEventListener("click", () => {
console.log("5. School page - bubbling");
});
1. School page - capturing 2. Student list - capturing 3. Priya button - target 4. Student list - bubbling 5. School page - bubbling
The capture listeners run before the target handler. The bubble listeners run after it.
When should you use capturing?
- When a parent must observe an event before its child.
- When event order matters for a specific interaction.
- When you need to inspect events early in propagation.
Most everyday click handlers use the default bubbling phase. Capturing is useful when you need earlier access to the event.
5. Event Bubbling in JavaScript
Event bubbling = the event travels from the target towards its ancestors.
It is the default behavior for many common events, including click. You do not need to pass true to listen during bubbling.
Example: Listen for clicks on the student list
const studentList = document.querySelector("#studentList");
studentList.addEventListener("click", (event) => {
console.log("Student list received a click");
});
When Priya's button is clicked, the event reaches the list. The list receives it during the bubbling phase.
Student list received a click
But the same parent listener also receives clicks from other children. We need to identify which button caused the event.
Use the event object to identify the clicked element
Event object = information about the event that happened.
The browser passes this object to your listener. It includes useful properties such as target, currentTarget and type.
studentList.addEventListener("click", (event) => {
console.log("Clicked element:", event.target.tagName);
console.log("Listener element:", event.currentTarget.id);
});
Clicked element: BUTTON Listener element: studentList
event.target points to the original event target. event.currentTarget points to the element whose listener is running.
6. Event Delegation in JavaScript
Event delegation = handling child events through one parent listener.
It works because many events bubble up through their parent elements. Instead of attaching listeners to every button, we attach one listener to the student list.
How event delegation works
- A student clicks a registration button.
- The click event bubbles to the student list.
- The parent checks which button was clicked.
- The parent handles the matching button.
The click bubbles to the parent, which finds the matching button and handles its student.
Implement event delegation
<ul id="studentList">
<li>
<button class="view-button" data-student="Priya">
View Priya
</button>
</li>
<li>
<button class="view-button" data-student="Ravi">
View Ravi
</button>
</li>
<li>
<button class="view-button" data-student="Lakshmi">
View Lakshmi
</button>
</li>
</ul>
const studentList = document.querySelector("#studentList");
studentList.addEventListener("click", (event) => {
const button = event.target.closest(".view-button");
if (!button || !studentList.contains(button)) {
return;
}
const studentName = button.dataset.student;
console.log("Viewing registration for:", studentName);
});
Viewing registration for: Priya Viewing registration for: Ravi Viewing registration for: Lakshmi
We attached only one listener to the student list. The parent handles all matching button clicks.
Why use closest()?
closest() checks the element and its ancestors for a matching selector.
Imagine a button contains an icon or a small text element. The user might click that inner element. In that case, event.target may point to the icon or text.
Calling closest(".view-button") finds the button that contains the clicked element. The contains() check ensures the matching button belongs to this student list.
<button class="view-button" data-student="Priya">
<span>View registration</span>
</button>
If the user clicks the span, event.target can be the span. The closest() call still finds the button.
7. Event Bubbling vs Capturing vs Delegation
| Concept | Direction or approach | Purpose |
|---|---|---|
| Event Capturing | Ancestor to target | Listen before the target phase |
| Event Bubbling | Target to ancestors | Let parent elements receive child events |
| Event Delegation | Uses bubbling | Handle many child events through one parent |
The idea to remember
- Event = an action in the browser.
- Event listener = a function waiting for an event.
- Event target = the original element where the event started.
- Current target = the element whose listener is running.
- Capturing = the event travels down towards the target.
- Bubbling = the event travels up towards the ancestors.
- Delegation = one parent handles events from matching children.
- closest() = finds the nearest matching element or ancestor.
8. Stop Event Propagation
Sometimes we do not want an event to continue through its normal path. JavaScript provides stopPropagation() for this purpose.
It stops the event from continuing to other listeners along the propagation path. It does not stop other listeners on the same element.
const studentList = document.querySelector("#studentList");
const priyaButton = document.querySelector("#priyaButton");
priyaButton.addEventListener("click", (event) => {
console.log("Priya button clicked");
event.stopPropagation();
});
studentList.addEventListener("click", () => {
console.log("Student list received the click");
});
Priya button clicked
The parent listener does not receive this click through bubbling. Use this method only when you need to stop propagation.
stopPropagation() vs preventDefault()
preventDefault() stops the browser's default action. It does not stop event propagation.
const registrationLink = document.querySelector("#registrationLink");
registrationLink.addEventListener("click", (event) => {
event.preventDefault();
console.log("Navigation was prevented");
});
Use preventDefault() when you need to stop a browser action. Use stopPropagation() when you need to stop the event travelling further.
| Method | What it stops | Example |
|---|---|---|
| stopPropagation() | Further propagation through the event path | Prevent a parent from receiving a child click |
| preventDefault() | The browser's default action | Prevent a link from navigating |
9. Common Mistakes and Best Practices
1. Confusing target and currentTarget
These properties are not always the same. The target is where the event started. The current target is where the active listener is attached.
2. Assuming every event bubbles
Not every browser event bubbles. Check the event's behavior before relying on delegation. For example, the focus event does not bubble, while focusin does.
3. Forgetting dynamically added elements
Listeners attached to existing buttons do not automatically attach to future buttons. Delegation solves this when new buttons are added inside the listened-to parent.
4. Using the wrong parent element
Attach the delegated listener to a parent that contains the intended buttons. Keep the selector specific to your feature.
5. Calling stopPropagation() without a clear reason
It can prevent other parts of your application from receiving events. Use it only when the event flow must stop.
6. Forgetting nested elements
A click can start on an icon or span inside a button. Use closest() to find the intended button.
7. Not checking the matching element
A parent may receive clicks from labels, empty spaces or other child elements. Check for a matching button before handling the event.
10. Performance and Architecture Considerations
Event delegation can reduce repeated listener setup. It can also simplify code for lists that change over time.
However, delegation is not automatically faster in every situation. A parent listener still needs to identify the correct target. A complex selector or a very large event handler can add work.
When should you choose each approach?
| Situation | Recommended approach | Reason |
|---|---|---|
| One fixed submit button | Direct listener | Simple and easy to understand |
| A list of many student buttons | Event delegation | One parent can handle all matching buttons |
| Buttons added after page load | Event delegation | New children can use the existing parent listener |
| Need to inspect an event before its target | Capturing | The listener runs during the capture phase |
| Need normal parent notification | Bubbling | Many common events bubble by default |
11. Interview Questions and Answers
Q1. What is event bubbling in JavaScript?
Answer: Event bubbling is the process where an event travels from its target to its parent elements. It allows parent elements to receive events from their children.
Q2. What is event capturing?
Answer: Event capturing is the phase where an event travels from the outer elements towards its target. We can enable it using capture: true or the third argument of addEventListener().
Q3. What is event delegation?
Answer: Event delegation means attaching one listener to a parent element. We use event bubbling to handle events from its child elements. It is useful for lists and dynamically added elements.
Q4. What is the difference between target and currentTarget?
Answer: target identifies the original event target. currentTarget identifies the element whose listener is currently running.
Q5. Does every event bubble in JavaScript?
Answer: No. Some events do not bubble. For example, focus does not bubble, but focusin does.
Q6. How do you stop event bubbling?
Answer: We can call event.stopPropagation(). It stops further propagation through the event path. It does not stop other listeners on the same element.
Q7. What is the difference between stopPropagation() and preventDefault()?
Answer: stopPropagation() stops further event propagation. preventDefault() stops the browser's default action. They solve different problems.
Q8. Why is event delegation useful for dynamic elements?
Answer: A delegated listener is attached to an existing parent. New matching children can use that listener without separate setup.
Q9. What does closest() do in event delegation?
Answer: closest() searches the target and its ancestors. It returns the nearest element matching the selector. It helps when a user clicks nested content inside a button.
Q10. Does event delegation work with every event?
Answer: No. It depends on the event's propagation behavior. For non-bubbling events, we may need capturing or another event that bubbles.
12. Hands-On Practice
Try these exercises to check your understanding. Use the school registration example first.
Exercise 1: Add a student button
BeginnerAdd a new student named Arjun to the registration list. Use the existing delegated listener. Confirm that his name appears when you click his button.
Exercise 2: Log the propagation order
BeginnerAdd capturing and bubbling listeners to the student list and its parent. Click a student button. Write down the order of the messages.
Exercise 3: Handle nested button content
IntermediateAdd an icon or span inside each registration button. Use closest() to identify the correct button.
Exercise 4: Add students dynamically
IntermediateCreate a new student button using document.createElement(). Add it to the student list. Confirm that the delegated listener handles it without another listener.
Exercise 5: Stop a specific click
AdvancedAdd a separate action inside a student row. Use stopPropagation() only for that action. Check which parent listeners still run.
13. What You Should Remember
- Events are actions that happen in the browser.
- Capturing moves from ancestors towards the target.
- The target phase is where the event reaches its target.
- Bubbling moves from the target towards its ancestors.
- Delegation uses bubbling to handle child events through one parent.
targetandcurrentTargetidentify different elements.closest()helps find a matching element inside nested content.- Use
stopPropagation()andpreventDefault()for different purposes.
14. Continue Learning
JavaScript events are an important part of interactive web development. They help you build forms, menus, tables, dashboards and dynamic interfaces.
Practise these examples in your browser. Change the element structure and observe the event order. This will make propagation easier to understand.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.