How to Create and Trigger Event in JavaScript
This tutorial is aimed to teach you the right techniques to create and trigger DOM events (also called synthetic events).
You can create events with the Event constructor like in the following example which uses the EventTarget.dispatchEvent() method:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h1 id="elemId">Welcome to W3Docs</h1>
<script>
document.addEventListener("welcome", function(event) {
alert("Hi, " + event.target.tagName); // Hi H1
});
let event = new Event("welcome", {
bubbles: true
});
elemId.dispatchEvent(event);
</script>
</body>
</html>
The addEventListener() initializes a function that will be called whenever the defined event is dispatched to the target.
To append additional data to the event object, you can use the CustomEvent interface and the detail property to pass custom data:
let event = new CustomEvent('eventName', {
detail: elem.prop.name
});
Then you can access the specified additional data in the event listener by using the following code:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h1 id="elemId">Welcome to W3Docs</h1>
<script>
elemId.addEventListener("welcome", function(event) {
alert(event.detail.name);
});
elemId.dispatchEvent(new CustomEvent("welcome", {
detail: {
name: "W3Docs"
}
}));
</script>
</body>
</html>
It is often recommended to trigger an event from a child element:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="text"></input>
<script>
let text = document.querySelector('input');
const eventAwesome = new CustomEvent('awesome', {
bubbles: true,
detail: {
text: () => text.value
}
});
text.addEventListener('awesome', e => alert(e.detail.text()));
text.addEventListener('input', e => e.target.dispatchEvent(eventAwesome));
</script>
</body>
</html>
To create and dispatch events dynamically you can use the following code:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="text">
</textarea>
<script>
let inputText = document.querySelector('input');
inputText.addEventListener('awesome', e => alert(e.detail.text()));
inputText.addEventListener('input', function() {
this.dispatchEvent(new CustomEvent('awesome', {
bubbles: true,
detail: {
text: () => inputText.value
}
}))
});
</script>
</body>
</html>
The dispatchEvent
The dispatchEvent delivers an Event at the specified EventTarget, synchronously executing the affected EventListeners in an appropriate order. Unlike native events that are fired by the DOM and call event handlers asynchronously with the help of the event loop, the dispatchEvent execute event handlers synchronously.