Custom Events
Create and dispatch custom events
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);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
Use Cases
Benefits
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.
Practical Learning Notes for Custom Events
This JavaScript program is part of the "Events Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.