JavaScript Tutorial in Hindi #27 | Event Bubbling & Delegation (2025)

✅ 1. What is Event Bubbling?

  1. When an event happens on an element, it first runs on that element, then bubbles up to its parent, then the grandparent, and so on, up to the root (document).
  2. This means the same event triggers handlers on ancestor elements unless stopped.
html
CopyEdit
<div id="parent">
<button id="child">Click Me</button>
</div>
js
CopyEdit
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});

document.getElementById("child").addEventListener("click", () => {
console.log("Button clicked");
});

Clicking the button prints:

css
CopyEdit
Button clicked
Parent clicked

✅ 2. Real-Life Example of Event Bubbling

Imagine a nested set of boxes. If you tap the smallest box, the tap effect happens on that box and also on each box containing it, one by one, until the outermost box.

✅ 3. What is Event Delegation?

  1. Instead of adding event listeners to many child elements, add one listener to their parent.
  2. Use the event’s target property to determine which child was clicked.

Example:

js
CopyEdit
document.getElementById("parent").addEventListener("click", (event) => {
if (event.target.tagName === "BUTTON") {
console.log("Button clicked:", event.target.textContent);
}
});

✅ 4. Why Use Event Delegation? (Benefits)

  1. Performance: Fewer event listeners = less memory & faster page.
  2. Dynamic elements: Works even for elements added after the listener is set.
  3. Simpler code: Manage all child events in one place.

✅ 5. Interview Questions

🔸 What is event bubbling?

🔸 What is event capturing?

🔸 How does event delegation work?

🔸 Why is event delegation useful?

🔸 How can you stop event bubbling?

🔸 How do you get the actual target of an event?

🔸 What is the difference between event.target and event.currentTarget?