Guest Mode:

BCA Student Stories & UpdatesLive

You
Your StorySign in & share
Er. Manoj Kumar
D5
Er. ManojActive nowPages
Day 34Advanced JavaScript & Browser APIs2 Hours Practical
Push to GitHub to Complete

DOM Event Delegation, Event Bubbling & Dynamic List Architecture

In dynamic web applications, items like comments, chat messages, or table rows are created and removed constantly. Attaching individual event listeners to thousands of elements slows down the browser and wastes memory. Event Delegation solves this by letting events bubble up to a single parent listener.

Interactive Learning Roadmap

Day 34 Step-by-Step Practical Flow

🎯1. What You Will Learn Today

✔Master the three phases of DOM event propagation: Capturing, Target, and Bubbling.
✔Implement Event Delegation by attaching a single event listener to a parent container instead of hundreds of child nodes.
✔Identify target elements using event.target and locate ancestor components with Element.prototype.closest().
✔Distinguish between event.target (the element clicked) and event.currentTarget (the element listening).
✔Optimize web performance and eliminate memory leaks in large dynamic lists.
Day 34 MasterclassAdvanced JavaScript & Browser APIs

DOM Event Delegation, Event Bubbling & Dynamic List Architecture — Comprehensive Practical Guide

Har concept ko visual mental models, code anatomy aur practical industry tips ke sath samjhein.

Real-World Purpose Aur Zaroorat

In dynamic web applications, items like comments, chat messages, or table rows are created and removed constantly. Attaching individual event listeners to thousands of elements slows down the browser and wastes memory. Event Delegation solves this by letting events bubble up to a single parent listener.

Event Bubbling: When an element is clicked, the event triggers on the element and then bubbles up through its ancestors all the way to document.
Single Listener: Instead of attaching 100 listeners to 100 buttons, attach 1 listener to the parent <ul> container.
Dynamic Support: Event delegation automatically works for elements added to the DOM in the future without needing re-binding.
element.closest(selector): Traverses ancestors to find the nearest matching element, solving issues when clicking nested <i> icons inside buttons.
e.stopPropagation(): Halts bubbling up the DOM tree when you explicitly do not want parent handlers to fire.
Dimaag Mein Bithane Ka Model

"Imagine an apartment building with 100 residents: instead of hiring 100 security guards to stand outside each apartment door, you place one security guard at the main building entrance who checks everyone coming in."

💡 Pro Tip: Code ko ratta mat maaro; imagine karo ki browser har tag ko visually kaise draw karta hai.

👨‍🏫3. Teacher Demonstration Code

See how a single click handler on the table manages edit, delete, and star actions across all dynamically added rows.

Event Delegation with Element.prototype.closest()html
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #060c18; color: #fff; padding: 24px; }
    .card { max-width: 500px; margin: auto; background: #0c1328; border: 1px solid #1e293b; padding: 20px; border-radius: 12px; }
    ul { list-style: none; padding: 0; margin-top: 16px; }
    li { display: flex; align-items: center; justify-content: space-between; padding: 10px; background: #1e293b; margin-bottom: 8px; border-radius: 6px; }
    button { padding: 6px 10px; border-radius: 4px; border: none; cursor: pointer; font-weight: bold; }
    .btn-fav { background: #f59e0b; color: #000; margin-right: 6px; }
    .btn-del { background: #ef4444; color: #fff; }
  </style>
</head>
<body>
  <div class="card">
    <h3>👨‍🎓 BCA Student Directory</h3>
    <button id="addStudentBtn" style="background:#2563eb;color:#fff;">+ Add Student</button>
    <ul id="studentList">
      <li data-id="1"><span>Rahul Sharma</span><div><button class="btn-fav">⭐</button><button class="btn-del">Delete</button></div></li>
      <li data-id="2"><span>Priya Patel</span><div><button class="btn-fav">⭐</button><button class="btn-del">Delete</button></div></li>
    </ul>
  </div>

  <script>
    const list = document.getElementById("studentList");

    // ⚡ SINGLE EVENT LISTENER FOR ENTIRE LIST (Event Delegation)
    list.addEventListener("click", (e) => {
      const delBtn = e.target.closest(".btn-del");
      const favBtn = e.target.closest(".btn-fav");

      if (delBtn) {
        const row = delBtn.closest("li");
        const studentId = row.dataset.id;
        console.log("Deleted student with ID:", studentId);
        row.remove();
      }

      if (favBtn) {
        const row = favBtn.closest("li");
        row.style.background = row.style.background === "rgb(4, 170, 109)" ? "#1e293b" : "#04aa6d";
      }
    });

    document.getElementById("addStudentBtn").addEventListener("click", () => {
      const newId = Date.now();
      const li = document.createElement("li");
      li.dataset.id = newId;
      li.innerHTML = '<span>New Student (' + newId.toString().slice(-4) + ')</span><div><button class="btn-fav">⭐</button><button class="btn-del">Delete</button></div>';
      list.appendChild(li);
    });
  </script>
</body>
</html>

2. Hands-On Practical Lab: Follow Instructions in VS Code

Code like a professional software engineer! Follow the step-by-step instructions below in Visual Studio Code (VS Code) on your PC, test your output locally, and push to GitHub.

2 Coding Tasks
Interactive Coding TestAuto-Evaluates as you type

Day 34 Practical Task Test Studio

Test Score:1 / 2 Passed
1. Practical Task Specifications & Live Test Checklist:Type code below to pass tests
Task 1Implement e.target.closest Selector

Use e.target.closest(".btn-del") to detect if a delete button or any of its child icons were clicked.

✔ PASSED
Task 2Access dataset from Ancestor Element

Extract the custom data-id attribute using element.closest("li").dataset.id.

⏳ WAITING
2. Type HTML & CSS Code:index.html
index.html
⚡ Real-Time Testing Active
Tab inserts 2 spaces • Live DOM refresh379 chars
Live Browser Output:
🔒 http://localhost:5500/index.html
Live
Renders live HTML & CSS typed on the left.
Interactive Bug Detective

The Nested Icon Inside Button Click Bug

Tap or click on the exact line below that contains the error:

Click any code line
⚠️ Broken Code Inspector
Tap buggy line
1
// HTML: <button class="delete-btn"><i class="icon">🗑️</i> Delete</button>
2
3
list.addEventListener("click", (e) => {
4
// ❌ Bug: If user clicks the <i> icon, e.target is the <i> element, NOT the button!
5
if (e.target.className === "delete-btn") {
6
e.target.parentElement.remove();
7
}
8
});
Stuck? Need a detective clue before checking the solution?

Senior Developer Forensic Analysis:

When a button has inner elements (like icons or spans), clicking the icon makes e.target refer to the inner element. Checking e.target.className === "delete-btn" fails because e.target is the <i> tag, not the <button>.

Golden Rule: Always validate code syntax and security attributes before pushing to GitHub!

📝Independent Practice: Assignment

📄 index.html

Interactive University Course Syllabus Checklist with Event Delegation

  • •Build a dynamic syllabus topic checklist with 5 initial subjects.
  • •Use Event Delegation on the container to handle marking topics as Completed, Bookmarked, or Deleted.
  • •Add an "+ Add Topic" input that inserts new checklist items dynamically; verify that new items respond to clicks immediately without re-attaching listeners.
  • •Display live statistics: Total Topics, Completed Topics, and Percentage Complete.
Submission Evaluation Criteria: Push index.html and app.js to your GitHub repository under day-34.
Exact Assignment Solution Code: index.html

Open Visual Studio Code on your PC (code .), create index.html, paste this complete step-by-step verified code, test in your browser, and push to your GitHub repo:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>BCA Day 34 - Event Delegation Syllabus</title>
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #060c18; color: #fff; padding: 24px; }
    .card { max-width: 520px; margin: auto; background: #0c1328; border: 1px solid #1e293b; padding: 24px; border-radius: 12px; }
    .input-row { display: flex; gap: 8px; margin-bottom: 16px; }
    input { flex: 1; padding: 10px; background: #060c18; border: 1px solid #334155; color: #fff; border-radius: 6px; }
    button { padding: 10px 16px; background: #2563eb; color: #fff; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; }
    ul { list-style: none; padding: 0; margin-top: 14px; }
    li { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px; background: #1e293b; margin-bottom: 8px; border-radius: 6px; }
    li.done span { text-decoration: line-through; opacity: 0.6; }
    .btn-done { background: #10b981; }
    .btn-del { background: #ef4444; margin-left: 6px; }
  </style>
</head>
<body>
  <div class="card">
    <h2>📚 BCS-011 Syllabus Checklist</h2>
    <div class="input-row">
      <input type="text" id="topicInput" placeholder="Add syllabus unit or chapter..." />
      <button id="addBtn">Add</button>
    </div>
    <ul id="checklist">
      <li data-id="1"><span>Unit 1: Computer Fundamentals</span><div><button class="btn-done">✓</button><button class="btn-del">✕</button></div></li>
      <li data-id="2"><span>Unit 2: Memory & Storage Devices</span><div><button class="btn-done">✓</button><button class="btn-del">✕</button></div></li>
    </ul>
  </div>

  <script>
    const checklist = document.getElementById("checklist");

    // Single Delegated Listener
    checklist.addEventListener("click", (e) => {
      const doneBtn = e.target.closest(".btn-done");
      const delBtn = e.target.closest(".btn-del");

      if (doneBtn) {
        const item = doneBtn.closest("li");
        item.classList.toggle("done");
      }

      if (delBtn) {
        const item = delBtn.closest("li");
        item.remove();
      }
    });

    document.getElementById("addBtn").addEventListener("click", () => {
      const input = document.getElementById("topicInput");
      const text = input.value.trim();
      if (!text) return;

      const li = document.createElement("li");
      li.dataset.id = Date.now();
      li.innerHTML = '<span>' + text + '</span><div><button class="btn-done">✓</button><button class="btn-del">✕</button></div>';
      checklist.appendChild(li);
      input.value = "";
    });
  </script>
</body>
</html>
Verified Assignment Code Solution (100% Tested & Ready to Run)

🎓4. Viva Check: Mandatory Conceptual Test

What is the main advantage of Event Delegation over adding event listeners directly to individual child elements?

5. Mandatory Step: Push to GitHub to Unlock Next Lesson

Target Repo: html-css-projects

Windows 11 Terminal / VS Code
1$
mkdir day-34
Create a new project folder (day-34)
2$
cd day-34
Change working directory to day-34
3$
git checkout -b feature/day-34-event-delegation
4$
git add index.html
5$
git commit -m "feat(day-34): implement dom event delegation and bubbling architecture"
Commit staged changes with a descriptive message
6$
git push origin feature/day-34-event-delegation
Push local commits directly to your remote GitHub repository
⌨️ Paste into terminal:Ctrl + V✨ Word wrap active (no horizontal cutoff)
Completion Prerequisites VerificationIncomplete Steps
Google Login
✔ Required
VS Code Implementation
Step 4 Viva Check
Own GitHub Project
Required

Exact GitHub Setup Guide & Expected Structure

Day 34 Requirements

Follow these exact folder and file names to prevent verification errors.

1. GitHub Repository
html-css-projects
Must be set to Public
2. Exact FolderNEW
day-34/ or bca-day-34/
Create inside repo root
3. Exact File NameREQUIRED
index.html
⚠️ No spaces or custom names
4. What to Submit Below
https://github.com/YOU/html-css-projects
Or direct link to index.html
Terminal Commands to Create & Push Day 34
1$
# 1. Enter your repository directory
2$
cd html-css-projects
Change working directory to html-css-projects
3$
# 2. Create the exact folder for Day 34
4$
mkdir day-34
Create a new project folder (day-34)
5$
cd day-34
Change working directory to day-34
6$
# 3. Create your code file: index.html
7$
# (Write your Day 34 homework code inside index.html)
8$
# 4. Save, stage, commit and push to GitHub:
9$
git add .
Stage all modified files and new assets for commit
10$
git commit -m "Day 34: DOM Event Delegation, Event Bubbling & Dynamic List Architecture"
Commit staged changes with a descriptive message
11$
git push origin main
Push local commits directly to your remote GitHub repository
⌨️ Paste into terminal:Ctrl + V✨ Word wrap active (no horizontal cutoff)
How to Avoid "Could not find your practical code file" Errors:
1.Use Lowercase index.html: Avoid spaces or custom names like Alan Turing..html or Index.HTML. Linux/GitHub servers are strictly case-sensitive.
2.Separate Day Folders: Create a new folder day-34/ for today so you don't overwrite previous days.
3.Ensure Public Visibility: If your GitHub repo is Private, automated validation cannot inspect your code. Set it to Public.
4.Check on GitHub Website: Before clicking "Verify", open your repo in Google Chrome to confirm your files were pushed to branch main.
📁 github.com/YOUR_USERNAME/html-css-projects
Branch: main
README.md# BCA Practical Portfolio overview
day-01/Day 1 Prior Lesson
└──index.html
day-02/Day 2 Prior Lesson
└──index.html
day-03/Day 3 Prior Lesson
└──index.html
day-04/Day 4 Prior Lesson
└──index.html
day-05/Day 5 Prior Lesson
└──index.html
day-06/Day 6 Prior Lesson
└──index.html
day-07/Day 7 Prior Lesson
└──index.html
day-08/Day 8 Prior Lesson
└──index.html
day-09/Day 9 Prior Lesson
└──index.html
day-10/Day 10 Prior Lesson
└──index.html
└──styles.css
day-11/Day 11 Prior Lesson
└──index.html
day-12/Day 12 Prior Lesson
└──index.html
day-13/Day 13 Prior Lesson
└──index.html
day-14/Day 14 Prior Lesson
└──index.html
day-15/Day 15 Prior Lesson
└──index.html
day-16/Day 16 Prior Lesson
└──index.html
day-17/Day 17 Prior Lesson
└──index.html
day-18/Day 18 Prior Lesson
└──index.html
day-19/Day 19 Prior Lesson
└──index.html
day-20/Day 20 Prior Lesson
└──index.html
└──styles.css
day-21/Day 21 Prior Lesson
└──index.html
day-22/Day 22 Prior Lesson
└──index.html
day-23/Day 23 Prior Lesson
└──index.html
day-24/Day 24 Prior Lesson
└──index.html
day-25/Day 25 Prior Lesson
└──index.html
day-26/Day 26 Prior Lesson
└──index.html
day-27/Day 27 Prior Lesson
└──index.html
day-28/Day 28 Prior Lesson
└──index.html
day-29/Day 29 Prior Lesson
└──index.html
day-30/Day 30 Prior Lesson
└──index.html
└──styles.css
day-31/Day 31 Prior Lesson
└──index.html
day-32/Day 32 Prior Lesson
└──index.html
day-33/Day 33 Prior Lesson
└──index.html
day-34/✨ CREATE THIS FOLDER FOR TODAY (Day 34)
└──index.htmlMust contain:
Sequential Progression Enforced

You are welcome to read all notes, inspect code snippets, and practice all exercises of Day 34 freely! To officially submit your GitHub repository and unlock subsequent days in your portfolio, please complete Day 33: JavaScript Timers: setTimeout, setInterval & Digital Clock / Countdown Engine first.

Complete Day 33 First
Curriculum & Practical Systems Authored by Er. Manoj Kumar
NextSem Academy • BCA Practical Learning Portal