JAVASCRIPT
Creating and Dispatching Custom DOM Events
Learn to create and dispatch custom events in the DOM, enabling decoupled communication between different parts of your JavaScript application.
/**
* Dispatches a custom event on a target element.
* @param {HTMLElement} targetElement The element to dispatch the event on.
* @param {string} eventName The name of the custom event.
* @param {Object} [detail={}] Optional data to pass with the event.
* @param {boolean} [bubbles=true] Whether the event should bubble up the DOM tree.
* @param {boolean} [cancelable=true] Whether the event can be cancelled.
*/
function dispatchCustomDomEvent(targetElement, eventName, detail = {}, bubbles = true, cancelable = true) {
const customEvent = new CustomEvent(eventName, {
detail: detail,
bubbles: bubbles,
cancelable: cancelable
});
targetElement.dispatchEvent(customEvent);
console.log(`Custom event '${eventName}' dispatched on`, targetElement);
}
// --- Example Usage ---
const myDiv = document.getElementById('myContainer'); // Assuming <div id="myContainer"></div>
if (myDiv) {
// 1. Listen for the custom event
myDiv.addEventListener('dataLoaded', (event) => {
console.log('Caught dataLoaded event!');
console.log('Event detail:', event.detail);
if (event.detail.success) {
console.log('Data processed successfully:', event.detail.data);
} else {
console.error('Data loading failed:', event.detail.error);
}
});
// 2. Dispatch the custom event after some asynchronous operation
setTimeout(() => {
console.log('Simulating data loading completion...');
dispatchCustomDomEvent(myDiv, 'dataLoaded', {
success: true,
data: { userId: 123, username: 'js_expert' },
timestamp: new Date().toISOString()
});
}, 1000);
// Example of a cancelable event
myDiv.addEventListener('userAction', (event) => {
if (event.detail.userId === 456) {
console.log('Cancelling userAction for user 456.');
event.preventDefault(); // Prevent default action (if any)
}
console.log('User action event:', event.detail);
});
setTimeout(() => {
dispatchCustomDomEvent(myDiv, 'userAction', { userId: 456, action: 'delete' });
dispatchCustomDomEvent(myDiv, 'userAction', { userId: 789, action: 'edit' });
}, 2000);
} else {
console.error('Element with ID "myContainer" not found.');
}
How it works: This snippet demonstrates how to create and dispatch custom events in the DOM, enabling a powerful form of decoupled communication within your web application. Using `new CustomEvent()` allows you to define a new event with a unique name and attach arbitrary data via the `detail` property. The `dispatchEvent()` method then fires this event on a specified DOM element. Components or modules can listen for these custom events using `addEventListener()`, reacting to application-specific actions or state changes without direct method calls, promoting modularity and flexibility.