LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

JavaScript Events – Event Bubbling, Capturing and Delegation

JavaScript Events, Event Bubbling, Event Capturing and Event Delegation. An event is an action performed by a user, such as clicking a button or typing in a textbox. When an event happens, JavaScript decides how that event travels through HTML elements.

JavaScript Events – Event Bubbling, Capturing and Delegation

TL;DR: JavaScript events describe how browser actions reach your code. Event capturing moves from the outer element towards the target. Event bubbling moves from the target towards its ancestors. Event delegation uses bubbling to handle many child events through one parent listener.

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

JavaScript – A simple click listener
const registerButton = document.querySelector("#registerButton");

registerButton.addEventListener("click", () => {
  console.log("Registration button clicked");
});
Expected output after clicking the button
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.

HTML – Three student registration buttons
<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>
JavaScript – Attach a listener to every button
const buttons = document.querySelectorAll(".view-button");

buttons.forEach((button) => {
  button.addEventListener("click", (event) => {
    console.log(
      "Viewing registration for:",
      event.currentTarget.dataset.student
    );
  });
});
Expected output – Click each button in order
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?

  1. We create many separate event listeners.
  2. New buttons need their own listeners.
  3. Removing or replacing elements needs extra care.
  4. Listener setup becomes harder to maintain.
  5. 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:

  1. Capturing: The event travels from the outer page towards the clicked element.
  2. Target: The event reaches the element that was clicked.
  3. Bubbling: The event travels back through its parent elements.

Let's follow a click on Priya's registration button.

One click travels through the DOM DocumentThe whole browser page Student ListParent element: #studentList Priya Registration ButtonThe clicked target Click Handler on the ButtonApplication code responds CAPTURING ↓ TARGET BUBBLING ↑ Conceptual view: propagation passes through ancestors and the target.

The event travels down during capturing, reaches the target, then travels upward during bubbling.

Remember: Capturing and bubbling are propagation phases. They do not mean two separate clicks. They describe different parts of the same event's journey.

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

HTML – The registration page structure
<div id="schoolPage">
  <ul id="studentList">
    <li>
      <button id="priyaButton">View Priya</button>
    </li>
  </ul>
</div>
JavaScript – Listen during the capture phase
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");
});
Expected output – Click the Priya button
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

JavaScript – A parent listens for child clicks
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.

Expected output – Click Priya's button
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.

JavaScript – Inspect the event target
studentList.addEventListener("click", (event) => {
  console.log("Clicked element:", event.target.tagName);
  console.log("Listener element:", event.currentTarget.id);
});
Expected output – Click the Priya button
Clicked element: BUTTON
Listener element: studentList

event.target points to the original event target. event.currentTarget points to the element whose listener is running.

Important difference: The target can be a child inside a button. The current target remains the element where you attached the listener.

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

  1. A student clicks a registration button.
  2. The click event bubbles to the student list.
  3. The parent checks which button was clicked.
  4. The parent handles the matching button.
One parent handles every student button Student ListOne click listener on the parent Find the Clicked Buttonevent.target.closest(".view-button") Handle the RegistrationRead the student's data attribute BUBBLES UP MATCH The parent handles clicks from all matching child buttons.

The click bubbles to the parent, which finds the matching button and handles its student.

Implement event delegation

HTML – Student registrations
<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>
JavaScript – One listener handles every button
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);
});
Expected output – Click the three buttons
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.

Example – A click on nested button content
<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

How the three event concepts differ
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.

JavaScript – Stop the click from bubbling further
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");
});
Expected output – Click Priya's button
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.

JavaScript – Prevent a link from navigating
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.

Two methods with different responsibilities
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.

Best practice: Use direct listeners for a few stable controls. Use delegation for repeated or dynamically added child elements. Choose capturing only when the earlier event phase matters.

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?

Practical choices for a web application
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

Beginner

Add 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

Beginner

Add 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

Intermediate

Add an icon or span inside each registration button. Use closest() to identify the correct button.

Exercise 4: Add students dynamically

Intermediate

Create 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

Advanced

Add 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.
  • target and currentTarget identify different elements.
  • closest() helps find a matching element inside nested content.
  • Use stopPropagation() and preventDefault() for different purposes.
Final takeaway: Learn the event path before writing complex handlers. Use bubbling when parent elements need child events. Use capturing when you need to listen earlier. Use delegation when many child elements share the same behavior.

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.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.