Custom Events
Create and dispatch custom events
IntermediateTopic: Events Programs
JavaScript Custom Events Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Create custom event
const customEvent = new CustomEvent('myCustomEvent', {
detail: { message: 'Hello from custom event', data: 123 },
bubbles: true,
cancelable: true
});
// Listen for custom event
document.addEventListener('myCustomEvent', function(event) {
console.log('Custom event received:', event.detail);
console.log('Message:', event.detail.message);
console.log('Data:', event.detail.data);
});
// Dispatch custom event
document.dispatchEvent(customEvent);
// Method 2: Custom event on specific element
const button = document.getElementById('myButton');
button.addEventListener('buttonClicked', function(e) {
console.log('Button custom event:', e.detail);
});
const buttonEvent = new CustomEvent('buttonClicked', {
detail: { buttonId: 'myButton', timestamp: Date.now() }
});
button.dispatchEvent(buttonEvent);
// Method 3: Event with data
const dataEvent = new CustomEvent('dataUpdate', {
detail: {
userId: 123,
action: 'update',
payload: { name: 'John', age: 30 }
}
});
document.addEventListener('dataUpdate', function(e) {
console.log('User ID:', e.detail.userId);
console.log('Action:', e.detail.action);
console.log('Payload:', e.detail.payload);
});
document.dispatchEvent(dataEvent);
// Method 4: Event with validation
function createValidatedEvent(type, data) {
if (!data || typeof data !== 'object') {
throw new Error('Data must be an object');
}
return new CustomEvent(type, {
detail: data,
bubbles: true,
cancelable: true
});
}
const validatedEvent = createValidatedEvent('validated', { value: 42 });
document.dispatchEvent(validatedEvent);Output
Custom event received: { message: 'Hello from custom event', data: 123 }
Message: Hello from custom event
Data: 123
User ID: 123
Action: update
Payload: { name: 'John', age: 30 }Understanding Custom Events
Custom events enable communication between components.
CustomEvent Constructor
•type: Event name
•detail: Custom data
•bubbles: Propagate up DOM
•cancelable: Can be prevented
Use Cases
•Component communication
•Decoupled architecture
•Custom notifications
•Plugin systems
Benefits
•Loose coupling
•Reusable components
•Better organization
•Event-driven architecture
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.