Making your own rules
You are not limited to listening only for built-in events like click or submit. You can create your own custom events to allow different parts of your application to communicate with each other.
1. Creating an Event
You can pass custom data inside the detail property.
let myEvent = new CustomEvent("userLogin", {
detail: { username: "JohnDoe" }, // Your custom data
bubbles: true // Should it bubble up the DOM tree?
});
2. Dispatching the Event
To " fire " the event, you dispatch it on a specific element (or the whole document).
document.dispatchEvent(myEvent);
3. Listening for it
You listen for it exactly like a normal click event!
document.addEventListener("userLogin", (e) => {
console.log("Welcome back, " + e.detail.username);
});
Important
Always use the detail parameter to pass your data. This is the standard, safe way to attach context to Custom Events without breaking the browser's event object structure.