Events are signals emitted by browser DOM nodes indicating user interaction (clicks, keystrokes, scrolls) or document lifecycle changes (DOM load, resource error). JavaScript handles events through event listeners and callbacks.
flowchart TD
Window["Window Node"] -->|1. Capturing Phase| Target["Target Element (e.g. Button)"]
Target -->|2. Target Phase| Target
Target -->|3. Bubbling Phase| Window
| Mechanism | Example Syntax | Pros | Cons |
|---|---|---|---|
| Inline HTML Attribute | <button onclick="doWork()"> |
Simple for quick tests | Pollutes HTML; bad separation of concerns. |
| DOM Property | btn.onclick = handler |
Simple JS binding | Only ONE handler allowed per event type. |
addEventListener() |
btn.addEventListener('click', handler) |
Best Practice: Multiple handlers, options, removal | Requires cleanup to prevent leaks. |
// Demonstrating Event Listeners and Propagation Control
document.addEventListener("DOMContentLoaded", () => {
const container = document.createElement("div");
container.id = "btn-container";
container.style.padding = "20px";
container.style.background = "#f0f0f0";
const actionBtn = document.createElement("button");
actionBtn.id = "action-btn";
actionBtn.textContent = "Click Me";
container.appendChild(actionBtn);
document.body.appendChild(container);
// 1. Adding Event Listener to Button (Target)
actionBtn.addEventListener("click", (event) => {
console.log("Button clicked!");
console.log(`Event Target ID: ${event.target.id}`);
// Stop event from bubbling up to container
// event.stopPropagation();
});
// 2. Adding Bubbling Listener to Container (Event Delegation)
container.addEventListener("click", (event) => {
console.log("Container received bubbled click event!");
});
// 3. Dispatching Custom Event
const customEvent = new CustomEvent("userLoggedIn", {
detail: { userId: 99, role: "admin" }
});
document.addEventListener("userLoggedIn", (event) => {
console.log(`Custom Event Caught! User ID: ${event.detail.userId}`);
});
document.dispatchEvent(customEvent);
});
addEventListener(): Never write inline onclick attributes in HTML markup.removeEventListener(): Remove listeners when components unmount to prevent memory leaks in Single Page Applications (SPAs).What is the difference between event.preventDefault() and event.stopPropagation()?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.