Topic 03 / 10

Event Handling, Bubbling & Event Delegation

1. Simple Definition

Event webpage par hone wala koi bhi action hota hai (jaise user ka mouse click karna, keyboard key dabana, ya page scroll karna). Event Listener wo watchman hota hai jo element par baith kar kisi specific action ka wait karta hai aur action hote hi function chala deta hai. Event Delegation ek advanced pattern hai jahan hum 100 child buttons par alag listener lagane ke badle sirf 1 parent container par listener lagate hain.

2. Real-Life Analogy

🛎️ Doorbell Switch Aur Office Receptionist (Delegation)

Event Listener: Ghar ki doorbell — koi switch dabata hai (Event), switch circuit activate karta hai aur buzzer bajta hai (Callback function).
Event Delegation: Ek 10-manjil ki building me 100 officers hain. Har officer ke room ke bahar watchman bithane ke badle Ground Floor par sirf 1 smart Receptionist baithaya gaya hai. Koi bhi guest aaye, Receptionist e.target dekh kar decide kar leta hai ki kis officer ke paas bhejna hai!

3. Why Do We Need It?

Bina event listeners ke website par koi click, typing ya form submission kaam nahi karega. Aur bina Event Delegation ke dynamic items (jo baad me create hote hain) par click listeners kaam nahi karte.

4. Syntax

// 1. Standard Event Listener
const btn = document.querySelector("#submit-btn");
btn.addEventListener("click", (event) => {
  console.log("Button Clicked!", event.target);
});

// 2. Keyboard Event (Enter or Escape key)
window.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    closeModal();
  }
});

// 3. Stopping Default Behavior (e.g. form reload, link open)
form.addEventListener("submit", (e) => {
  e.preventDefault(); // Browser reload stopped!
});

5. Basic Example (Mastering Event Delegation)

<!-- Single listener on parent UL handles all 100+ items! -->
<ul id="item-list">
  <li data-id="1">Item 1 <button class="del-btn">Delete</button></li>
  <li data-id="2">Item 2 <button class="del-btn">Delete</button></li>
</ul>

<script>
  const list = document.querySelector("#item-list");

  // Event Delegation Magic:
  list.addEventListener("click", (e) => {
    // Check if clicked element is the delete button
    if (e.target.classList.contains("del-btn")) {
      const parentLi = e.target.closest("li");
      console.log("Deleting Item ID:", parentLi.dataset.id);
      parentLi.remove();
    }
  });
</script>

6. Output / Expected Result

  • Coffee Mug (₹299)
  • Notebook (₹99)

7. Code Explanation: Event Bubbling vs Capturing

  • Event Bubbling (Default): Jab aap kisi <button> par click karte hain, toh event button se shuru hokar paani ke bubble ki tarah upar uske parent <div>, fir <body>, fir window tak propagate hota hai.
  • Event Capturing: Opposite direction — event pehle window se neeche deep target element tak travel karta hai (rarely used).
  • e.stopPropagation(): Event ko upar parent tak bubble hone se rok deta hai (e.g. modal ke andar click hone par backdrop click trigger na ho).
  • e.target: Exactly wo element jispar user ne physical click kiya.
  • e.currentTarget: Wo element jispar addEventListener attach kiya gaya tha.

8. Real-World Example

Modal backdrop click: Modal ke grey background par click karne par modal close hota hai, lekin modal box ke andar click karne par e.stopPropagation() lagaya jata hai taaki box ke andar click karne par modal band na ho!

9. Common Mistakes

⚠️ Galti 1: HTML me onclick="myFunction()" likhna (Legacy)

HTML attributes me inline JS (onclick="...") likhna anti-pattern hai. Hamesha JS file me addEventListener use karein taaki separation of concerns maintain rahe aur multiple listeners lagaye ja sakein.

⚠️ Galti 2: Form submit par preventDefault() bhool jana

Agar aap form submit event me e.preventDefault() nahi lagate, toh page instantly reload ho jata hai aur saara JS state loss ho jata hai!

10. Best Practices

  • Dynamic lists (To-Do apps, comments) ke liye har item par listener lagane ke badle Event Delegation use karein.
  • Memory leaks se bachne ke liye jab components destroy hon toh removeEventListener call karein.

11. Try It Yourself

Playground me window.addEventListener("resize", ...) laga kar browser window ki live width print karein.

12. Challenge

Ek Accordion FAQ system banayein jo Event Delegation use karke kisi bhi question click ko handle kare aur sirf matching answer ko .classList.toggle('open') kare.

13. Interview Questions

💼 Q: Event Delegation ke do sabse bade fayde kya hain?

Answer:
1. Memory Optimization: Agar 1,000 table rows hain, toh 1,000 separate listeners memory me load karne ke bajaye sirf 1 single parent listener lagta hai (Fast & Lightweight).
2. Dynamic Elements: Agar future me JavaScript se naya 1,001st item create kiya jaye, toh uspar listener lagane ki zarurat nahi padti; wo automatically kaam karta hai!

14. Quick Revision

  • addEventListener("click", callback).
  • Events bubble upwards through parents.
  • Event Delegation uses e.target on parent.
  • e.preventDefault() stops browser default reloads.

15. FAQ

Q1. input event aur change event me kya fark hai?

input har single keystroke par realtime trigger hota hai. change sirf tab trigger hota hai jab user input se bahar click kare (blur ho jaye).

Q2. { once: true } option kya karta hai?

btn.addEventListener("click", fn, { once: true }) listener ko pehle click ke baad automatically self-remove kar deta hai.

Q3. Double click ke liye kaunsa event hai?

"dblclick" event.

Q4. Scroll event lagate waqt performance issue kyun aata hai?

Kyunki scroll per second 60 baar fire hota hai. Iske liye Debounce ya Throttle technique use ki jaati hai.

Q5. Custom Events kaise create karein?

new CustomEvent("myEvent", { detail: { ... } }) aur element.dispatchEvent() se.

Topic 03 / 10

Event Handling, Bubbling & Event Delegation

1. Simple Definition

Events are signals fired by the browser when something occurs (e.g. mouse clicks, key presses, scrolling, form submissions). Event Delegation is an architectural pattern that leverages Event Bubbling to listen for events on a common ancestor rather than attaching hundreds of individual listeners to child nodes.

2. Real-Life Analogy

🏢 Building Security Desk vs 100 Office Doormen

Instead of placing 100 individual security guards at every single room door on the 5th floor, you place a single security guard at the main lobby elevator (Event Delegation). Whenever anyone arrives on the floor, the lobby guard checks their badge (event.target) and directs them appropriately!

3. Event Bubbling & Capturing

When an event occurs on an element (e.g. a button), it traverses three phases:

  1. Capturing Phase: The event travels downwards from window to the target element.
  2. Target Phase: The event reaches the exact target element clicked.
  3. Bubbling Phase: The event bubbles upwards from the target all the way back up to window like an air bubble in water!

4. The Event Delegation Pattern

// Attach ONE single listener to the parent list
const todoList = document.querySelector("#todo-list");

todoList.addEventListener("click", (event) => {
  // Check if a delete button was clicked using .closest()
  const deleteBtn = event.target.closest(".delete-btn");
  if (!deleteBtn) return; // Exit if clicked elsewhere

  // Find and remove the parent task item
  const taskItem = deleteBtn.closest("li");
  taskItem.remove();
});

5. Essential Event Methods

form.addEventListener("submit", (e) => {
  e.preventDefault(); // Prevents browser from reloading page on submit!
});

button.addEventListener("click", (e) => {
  e.stopPropagation(); // Halts the event from bubbling up to parents
});

6. Common Mistakes

⚠️ Common Pitfall: Forgetting e.preventDefault() on forms

Default HTML form submissions reload the entire webpage, clearing your JavaScript memory state! Always call e.preventDefault() inside your form submit handler!

7. Best Practices

  • Always use addEventListener() instead of inline onclick="".
  • Use Event Delegation for dynamically generated elements (lists, cards, tables).
  • Leverage event.target.closest(selector) to handle clicks on nested SVG icons inside buttons.

8. Practice Exercise

🎯 Exercise: Delegation Gallery

Create an image thumbnail gallery with a single click listener on the parent container that displays the clicked image's full-size URL using event.target.dataset.fullUrl.

9. Interview Questions

💼 Q: What is the difference between event.target and event.currentTarget?

Answer: event.target is the exact deep element that was physically clicked by the user. event.currentTarget is the element to which the event listener was explicitly attached.

10. Summary / Cheat Card

  • addEventListener() listens for user and system events.
  • Events bubble upwards through parent ancestors.
  • Event delegation places one listener on an ancestor to manage all children.
  • e.preventDefault() stops default browser behaviors.

11. FAQ

Q1. Can you pass options to addEventListener?

Yes! Options include { once: true } (runs only once and auto-removes) and { passive: true } (improves scrolling performance).