Dispatching Custom Events in JavaScript
JavaScript allows you to create and dispatch custom events using the CustomEvent
constructor. This lets you define and trigger your own events, passing custom data if needed.
š¹ Creating and Dispatching a Custom Event
We use document.dispatchEvent()
or element.dispatchEvent()
to trigger an event.
✔ Example 1: Creating a Simple Custom Event
š Effect: Logs "Custom event triggered!"
when dispatched.
š¹ Using CustomEvent
to Pass Data
We can pass extra data using CustomEvent
and the detail
property.
✔ Example 2: Custom Event with Data
š Effect: Logs "User logged in: JohnDoe at [current time]"
.
š¹ Dispatching Events on Specific Elements
We can attach events to elements and dispatch them specifically.
✔ Example 3: Dispatching on an HTML Element
š Effect: Logs "Custom click detected!"
when the event is dispatched on the button.
š¹ Bubbling and Event Propagation
By default, custom events don’t bubble. To enable bubbling:
✔ Example 4: Enable Event Bubbling
š Effect: If the div
is inside <body>
, the event bubbles up and is detected by body
.
š¹ Cancelling a Custom Event
Use event.preventDefault()
and check event.defaultPrevented
.
✔ Example 5: Preventing Default Behavior
š Effect: Logs "Event was cancelled: true"
.
š¹ When to Use Custom Events?
✅ Component communication in JavaScript-based UI frameworks.
✅ Trigger custom actions when certain conditions are met.
✅ Pass data between different parts of an application.
š Mastering custom events makes your web applications more dynamic and interactive!