SyntaxStudy
Sign Up
JavaScript Intermediate 8 min read

Custom Events

Custom Events

Beyond the built-in DOM events, you can create and dispatch your own custom events. This enables loosely coupled component communication — one part of your application can emit a named event, and any other part can listen for it, without them being directly coupled.

Creating Custom Events

Use the CustomEvent constructor with an event name and an options object. The detail property of the options carries arbitrary payload data. Set bubbles: true to allow the event to bubble up the DOM.

Dispatching Events

Call element.dispatchEvent(event) to fire the event on a DOM element. Any listener registered for that event name on the element or its ancestors (if bubbling) will be triggered.

Listening for Custom Events

Custom events are listened for exactly like built-in events, using addEventListener with the event name as a string. Access the payload via event.detail inside the handler.

Example
const productCard = document.querySelector('.product-card');
const addToCartEvent = new CustomEvent('addToCart', {
  bubbles: true,
  detail: {
    productId: 42,
    name: 'Widget Pro',
    price: 29.99
  }
});
document.addEventListener('addToCart', function(e) {
  console.log('Product added:', e.detail.name);
  console.log('Price:', e.detail.price);
});
productCard.addEventListener('click', function() {
  productCard.dispatchEvent(addToCartEvent);
});
productCard.dispatchEvent(addToCartEvent);
Pro Tip

Custom events with bubbles: true act as a simple publish-subscribe mechanism within the DOM — any ancestor element can listen without tight coupling to the emitting element, which scales well in component-based architectures.