Advance JavaScript (DOM, BOM, Web API) / Document Object Model

Event Handling - Advanced

✅ dispatchEvent() — Manually Triggering Events

Normally, events are triggered by user actions (click, keypress, scroll).

dispatchEvent() allows you to trigger an event using JavaScript.

📌 Why dispatchEvent() is Useful

  • Simulate user actions

  • Automate UI behavior

  • Write tests

  • Trigger existing event listeners programmatically

🧠 How It Works (Step-by-Step)

1️⃣ You create an event object

2️⃣ You dispatch it on an element

3️⃣ All listeners for that event type run

4️⃣ Event follows normal event flow (bubbling/capturing)

⚠️ Important Notes

  • Does not physically click the mouse

  • Only triggers JavaScript listeners

  • Respects event bubbling & capturing

📌 Real-World Uses

✔ Unit testing

✔ Auto-trigger actions

✔ Simulating clicks in tutorials


✅ Custom Events — Creating Your Own Events

Custom Events allow you to define application-specific events like:

  • login

  • cartUpdated

  • themeChanged

📌 Why Custom Events Are Powerful

  • Loose coupling between components

  • Cleaner architecture

  • Better scalability

🧪 Basic Custom Event Example

const loginEvent = new CustomEvent("login", {
  detail: { user: "Bhaskar" }
});

// Listen for custom event
document.addEventListener("login", (event) => {
  console.log(event.detail.user);
});

// Dispatch event
document.dispatchEvent(loginEvent);
Bhaskar

🧠 Understanding detail

  • detail carries custom data

  • Available via event.detail

  • Helps pass information between components

🧪 Real-World Example — Component Communication

📌 When to Use Custom Events

✔ Component communication

✔ Decoupled systems

✔ Micro-frontend apps

✔ Plugin systems


✅ MutationObserver — Watching DOM Changes

MutationObserver allows you to observe changes in the DOM automatically.

📌 What Can It Observe?

  • Elements added or removed

  • Attribute changes

  • Text content changes

🧪 Basic Example

const observer = new MutationObserver(() => {
  console.log("DOM changed");
});

observer.observe(document.body, {
  childList: true,
  subtree: true
});

🧠 How It Works

1️⃣ Observer is created with a callback

2️⃣ You specify what to watch (observe)

3️⃣ When DOM changes → callback runs

🧪 Example — Detect Added Elements

🧩 Observer Options Explained

Option

Meaning

childList

Watch child add/remove

attributes

Watch attribute changes

subtree

Watch all descendants

characterData

Watch text changes

⚠️ Best Practices

✔ Disconnect when not needed

✔ Avoid heavy logic in callback

✔ Observe specific elements

observer.disconnect();

📌 Real-World Uses

✔ Dynamic content detection

✔ Framework internals (React, Vue)

✔ Ad blockers & extensions

✔ Chat apps & live feeds


🧠 Quick Comparison

Feature

Purpose

dispatchEvent()

Trigger events manually

Custom Events

App-specific communication

MutationObserver

Watch DOM changes