Events are used in almost every web application, such as the onclick event is used to execute some code when the user clicks on something. There are already numerous built-in events available to be used, but what if we want our custom event? Let us suppose we are creating a chat application, and we want to execute some code when the end-user sends some message. There is no built-in event to detect that. Here we need a custom event that can handle such custom scenarios.
Creating a Custom Event:
To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality.
The below steps are followed to create one using a new Event.
- We create an event using the Event constructor.
- We listen to this event using the addEventListener() method.
- We trigger or dispatch the event using element.dispatchEvent(eventName) method.
- A custom Event named start has now been created.
Syntax:
// To assign event
const startEvent = new Event("start");
// To trigger the event Listener
document.addEventListener("start", () => {
console.log("The start event was triggered")
});
// To trigger the Event
document.dispatchEvent(startEvent);
Example: We are creating an event that is triggered when the value of x is 5.
HTML
<!DOCTYPE html>
<html>
<head>
<title>JavaScript custom Events</title>
</head>
<body>
<script>
let x = 5;
const event = new Event("start");
document.addEventListener('start', () => {
console.log("Start event triggered")
});
if (x == 5) {
document.dispatchEvent(event);
}
</script>
</body>
</html>
Output:
"Start event triggered"
Creating a custom event using CustomEvent:
Creating custom events using the CustomEvent interface has an advantage as it can send custom data. The below steps are followed in order to create a new CustomEvent.
- We create a custom event using the CustomEvent constructor.
- This takes two arguments, the first is the name of the event and the second is an object that contains the data. The property name inside the object name should be named detail otherwise it won't work.
- We create a listener for this event.
- We trigger or dispatch the event.
- A custom event that contains data has been created.
Syntax:
// To assign event
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});
// To trigger the event Listener
document.addEventListener('start', (e)=>{
console.log(
`start event triggered on platform :
${e.detail.platform}`
);
});
// To trigger the Event
document.dispatchEvent(event);
Example: In this example, we are creating a custom event that triggers when the value of x is 5.
HTML
<!DOCTYPE html>
<html>
<head>
<title>JavaScript custom Events</title>
</head>
<body>
<script>
let x = 5;
const event = new CustomEvent("start", {
detail: {
platform: "GeeksforGeeks"
}
});
document.addEventListener('start', (e) => {
console.log(
`Start event triggered on platform
${e.detail.platform}`
);
})
if (x == 5) {
document.dispatchEvent(event);
}
</script>
</body>
</html>
Output:
Start event triggered on platform GeeksforGeeks
Note: We are dispatching the event directly from the document using document.dispatchEvent('start'), but one can dispatch the event from any needed element like myBtn.dispatchEvent('start').
Similar Reads
JavaScript Events JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. HTML<html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </script> <body> <but
3 min read
What are JavaScript Events ? JavaScript Events are the action that happens due to the interaction of the user through the browser with the help of any input field, button, or any other interactive element present in the browser. Events help us to create more dynamic and interactive web pages. Also, these events can be used by t
6 min read
How to trigger events in JavaScript ? JavaScript is a high-level, interpreted, dynamically typed client-side scripting language. While HTML is static and defines the structure of a web page, JavaScript adds interactivity and functionality to HTML elements. This interaction is facilitated through events, which are actions or occurrences
2 min read
How to Handle JavaScript Events in HTML ? An Event is an action or occurrence recognized by the software. It can be triggered by the user or the system. Mostly Events are used on buttons, hyperlinks, hovers, page loading, etc. All this stuff gets into action(processed) with the help of event handlers. In this article, you will learn about d
3 min read
JavaScript addEventListener() with Examples The addEventListener() method is used to attach an event handler to an element in the DOM (Document Object Model). It listens for specific events (such as click, keydown, or submit) on that element and executes a function when the event occurs.Syntaxelement.addEventListener(event, function, useCaptu
9 min read
p5.js Events Complete Reference The p5.js events used to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model(DOM). Keyboard Description keyIsPressedIt is true if any key is pressed and false if no keys are pressed. keyIt always contains the value of the key which is recently p
1 min read
jQuery Events jQuery events are actions or occurrences that happen on a web page, such as clicks, hover, or keypress. jQuery provides methods to handle and respond to these events with ease. jQuery events are used to create dynamic web pages. Syntax: $(selector).method(function)Here We will explore some basic eve
4 min read
Node.js Events An event in NodeJS is an action or occurrence, such as a user click, a file being read, or a message being received, that NodeJS can respond to. Events are managed using the EventEmitter class, which is part of NodeJS's built-in events module. This allows NodeJS to react to various actions asynchron
7 min read
ES6 Events The ES6 Events are the part of every HTML element that contains a set of events that can trigger the JavaScript code. An Event is an action or occurrence recognized by the software. It can be triggered by the user or the system. Mostly Events are used on buttons, hyperlinks, hovers, page loading, et
4 min read
How to use DOM and Events ? DOM (Document Object Model), a programming interface that is used to connect web pages to scripts by representing the structure of a document such as HTML documents. It defines the way a document is to be accessed and manipulated and also defines the logical structure of documents.The way DOM repres
3 min read