JavaScript Advanced Day 5: Advanced DOM & Event Handling

Goal of this Day

Today you will learn:

By the end, you will manage complex UI interactions effectively.

Step 1: Event Delegation

Attach a single event listener to a parent element:


document.querySelector("#parent").addEventListener("click", e => {
  if(e.target.tagName === "BUTTON") alert("Button clicked!");
});

Step 2: Dynamic Elements

New elements can be handled by delegating events to parent:


const parent = document.querySelector("#parent");
const btn = document.createElement("button");
btn.textContent = "Click me";
parent.appendChild(btn);

Step 3: Custom Events

Create and dispatch custom events:


const event = new CustomEvent("myEvent", { detail: { message: "Hello!" } });
document.dispatchEvent(event);

document.addEventListener("myEvent", e => {
  console.log(e.detail.message); // Hello!
});

Step 4: Manipulating Classes & Attributes

Use classList and setAttribute:


const div = document.querySelector("#box");
div.classList.add("active");
div.setAttribute("data-id", 123);

Practice


document.querySelector("#parent").addEventListener("click", e => {
  if(e.target.tagName === "BUTTON") alert("Button clicked!");
});

Task

Build a dynamic list:

Example:


// HTML
// <ul id="list"></ul>
// <button id="add">Add Item</button>

const list = document.querySelector("#list");
const addBtn = document.querySelector("#add");

addBtn.addEventListener("click", () => {
  const li = document.createElement("li");
  li.innerHTML = `Item `;
  list.appendChild(li);
});

// Event delegation for remove buttons
list.addEventListener("click", e => {
  if(e.target.classList.contains("remove")) {
    e.target.parentElement.remove();
  }
});