Skip to main content

Lesson 6 of 9

Custom Events & Component Communication

Custom Events let HTML components communicate with each other without tight coupling. A component dispatches a custom event with data, and any parent element can listen for it. This is the same pattern React uses (props down, events up) but built into the browser.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Custom Events Pattern

Dispatching a custom event:
element.dispatchEvent(new CustomEvent('cart-updated', {
detail: { itemCount: 5, total: 99.99 },
bubbles: true, // Event bubbles up to parents
composed: true // Event crosses shadow DOM boundary
}));

Listening for the event:
document.addEventListener('cart-updated', (e) => {
console.log(e.detail.itemCount); // 5
console.log(e.detail.total); // 99.99
});

Communication patterns:
1. Parent → Child: Set attributes/properties on child element
2. Child → Parent: Dispatch custom events (bubble up)
3. Sibling → Sibling: Use a shared event bus or store

Real-world example:
• Product card dispatches 'add-to-cart' with product details
• Cart widget listens for 'add-to-cart' and updates count
• Header receives bubbled event and updates cart badge

Diagram
Loading diagram…

Custom events allow encapsulated Web Components to communicate across DOM boundaries

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done