Thanks to visit codestin.com
Credit goes to coreui.io

How to dispatch a custom event in JavaScript

Creating and dispatching custom events enables powerful component communication and decoupled application architectures. With over 25 years of experience in software development and as the creator of CoreUI, I’ve built extensive event systems for complex UI interactions. From my expertise, the most effective approach is using the CustomEvent constructor with the dispatchEvent() method to create flexible, data-carrying events. This pattern allows components to communicate without tight coupling.

Use CustomEvent constructor and dispatchEvent() method to create and trigger custom events with data.

const customEvent = new CustomEvent('dataUpdated', {
  detail: { userId: 123, action: 'create' }
})
document.dispatchEvent(customEvent)

Here new CustomEvent('dataUpdated', { detail: ... }) creates a custom event with the name ‘dataUpdated’ and passes data through the detail property. The document.dispatchEvent(customEvent) method fires the event on the document, making it available to any listeners. Event listeners can access the custom data via event.detail, enabling rich communication between different parts of the application.

Best Practice Note:

This is the same approach we use in CoreUI components for inter-component communication and plugin architecture. Custom events provide excellent separation of concerns and make testing individual components much easier.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
JavaScript printf equivalent
JavaScript printf equivalent

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

Understanding Operator Precedence in JavaScript: Why Parentheses Matter with `??` and `?:`
Understanding Operator Precedence in JavaScript: Why Parentheses Matter with `??` and `?:`

How to capitalize the first letter in JavaScript?
How to capitalize the first letter in JavaScript?

Answers by CoreUI Core Team