Updated April 10, 2023
let customEvent = new CustomEvent("newEventName");
This is how the custom event is created normally. Its syntax is as below,
new CustomEvent(typeArg, customEventInit);
- typeArg : The typeArg parameter represents the name of the custom event we are defining.
- customEventInit: The customEventInit is an optional field that is holding a “detail” field which is again an optional field. This field holds the values related to the event.
Return Value: It returns an object of CustomEvent with the associated properties if specified with the customEventInit dictionary.
The custom events work in the same way as default events work. We can configure elements to listen to custom events in a similar way as default events by using the addEventListener() method. This is how a custom event is created and implemented,
First, a custom event is defined as below,
var customEvent = new CustomEvent('newEventName')
Once the object is created, the event is passed to the method dispatchEvent on the element on which we want to attach the event. This element will act as a target event.
The definition and implementation of a custom event are done until here, after that the event listener is added for this event just like any other event.
element.addEventListener('newEventName', function( event));
In this way, we can pass the event object whenever an event occurs and we can perform multiple activities as required.
Example #1 – Modify element data on an event
Here, we have defined a custom event to modify the text contents and its font size. We are calling function changeText() from the console to generate an event.
Example #2 – Trigger event using the button
Here, we have created a new custom event with detail as one text message. This event has been attached to the document itself. To trigger the event in this scenario, we have created a button. The button will trigger the event and cause a document to act upon click. In our case, we are replacing text with message details from the event itself.
- We can create custom events as per the specific functionality.
- This improves the maintenance of code as the same functionality is bind together.
- Custom events allow us to run the function outside of the script.
- It is possible to attach events in other file or script and run them.
- It is possible to attach multiple listeners to the same event.
- Separation of code from a script is possible as we don’t have to include event code in functions.
- The code gets decoupled and multiple scripts can use these events and also multiple developers can work effectively.