🟢 EasyDOM & Events📖 Theory Question

How do you create and dispatch Custom Events?

💡

Hint

new CustomEvent(name, { detail, bubbles }) — dispatch with element.dispatchEvent()

Full Answer

Custom Events let you create your own event types for loosely-coupled component communication.

// Create
const loginEvent = new CustomEvent('user:login', {
  detail: { userId: 42, name: 'Alice' }, // payload — any data
  bubbles: true,     // will bubble up the DOM
  cancelable: true   // can be preventDefault'd
});

// Dispatch
document.dispatchEvent(loginEvent);
// or: specificElement.dispatchEvent(loginEvent);

// Listen
document.addEventListener('user:login', (e) => {
  console.log(e.detail.name); // 'Alice'
  console.log(e.type);        // 'user:login'
});

// Real-world: decoupled component communication
class Cart {
  addItem(item) {
    this.items.push(item);
    window.dispatchEvent(new CustomEvent('cart:updated', {
      detail: { items: this.items, count: this.items.length }
    }));
  }
}

// Navbar listens independently
window.addEventListener('cart:updated', ({ detail }) => {
  cartBadge.textContent = detail.count;
});
💡 Namespace your events with colons (user:login, cart:updated) to avoid collisions with native events. This is a lightweight pub/sub without a library.

More DOM & Events Questions

🟢 EasyExplain event delegation and why it is useful.→🟢 EasyWhat is the difference between event.stopPropagation() and event.preventDefault()?→🟢 EasyWhat is the difference between event bubbling and event capturing?→🟡 MediumWhat is MutationObserver and when do you use it?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint