Introduction to JavaScript Custom Events
JavaScript provides a way to define and execute events according to user needs which we call it custom events. As JavaScript provides default events on target elements like mouse hover, select dropdown the default handler function is executed, but in case of custom events, we can define our event and execute our execution function. This provides users more flexibility in developing the code and also improves maintenance of the code. These events are not fired by the browser therefore they are also known as synthetic events. In this article, we will see how to create custom events and dispatch them.
Syntax:
let customEvent = new CustomEvent("newEventName");
This is how the custom event is created normally. Its syntax is as below,
new CustomEvent(typeArg, customEventInit);
Parameters:
- 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.
How do Custom Events work in JavaScript?
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.
element.dispatchEvent(customEvent );
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.
Examples of Custom Events in JavaScript
Below are the different examples to implement Custom Events in JavaScript.
Example #1 – Modify element data on an event
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>
JavaScript Custom Events
</title>
<style>
.body-data {
border : #81D4FA 2px solid;
background-color : #03a9f400;
text-align : left;
padding-left : 20px;
height : auto;
width : auto;
}
.resultText {
margin: 0 0 3px 0;
padding: 0px;
display: block;
font-weight: bold;
}
.heading {
font-weight: bold;
border-bottom: 2px solid #ddd;
font-size: 15px;
width: 98%;
}
</style>
</head>
<body>
<div class = "body-data" >
<div class = "heading" >
<h2> JavaScript Custom Events </h2>
</div>
<div class = "resultText" >
<p id = "result1" > Default Text </p>
</div>
</div>
<script type = "text/javascript">
var textElement = document.getElementById( 'result1' );
// Adding defined custom event on the text field element
textElement.addEventListener( 'newEventName' , function( event ) {
textElement.innerHTML = event.detail.newText;
textElement.style.fontSize = event.detail.fontSize;
} ) ;
function changeText( t, s ) {
// Creating new event name newEventName with event object detail containing
// new text to be updated and font size to change dynamically
var customEvent = new CustomEvent( 'newEventName', {
detail : {
newText: t,
fontSize: s
}
} );
// dispatching the event on element on which we want it to register
textElement.dispatchEvent( customEvent );
}
</script>
</body>
</html>
Output:
Before Event:
After 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
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>
JavaScript Custom Events
</title>
<style>
.body-data {
border : #81D4FA 2px solid;
background-color : #03a9f400;
text-align : left;
padding-left : 20px;
height : auto;
width : auto;
}
.resultText {
margin: 0 0 3px 0;
padding: 0px;
display: block;
font-weight: bold;
}
.heading {
font-weight: bold;
border-bottom: 2px solid #ddd;
font-size: 15px;
width: 98%;
}
</style>
</head>
<body>
<div class = "body-data" >
<div class = "heading" >
<h2> JavaScript Custom Events </h2>
</div>
<div class = "resultText" >
</br>
<button> Trigger Event </button>
<p id = "result1" > Default Text </p>
</div>
</div>
<script type = "text/javascript">
// Add an event listener
document.addEventListener( 'myEvent' , function( e ) {
console.log( e.detail );
document.getElementById( 'result1').innerHTML = e.detail;
} );
function fireEvent( ) {
// create new custom event
var event = new CustomEvent( 'myEvent' , {
"detail" : "Trigger custom event Example "
});
// Dispatch the custom event
document.dispatchEvent( event );
}
// button to trigger the event
document.getElementsByTagName( "button" )[0].onclick = function() {
fireEvent();
}
</script>
</body>
</html>
Output:
Before Click:
After Click:
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.
Advantages
- 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.
Conclusion
The custom events are nothing but the events which are created by developers themselves. These are nothing different than default events available in JavaScript. Custom events allow us to separate the code from scripts or functions and they can be triggered from outside as well. These events are also known as synthetic events.