HTML Element .dispatchEvent() Since: DOM Level 2(2000)
A method that programmatically fires an event on an HTML element. By combining element.dispatchEvent() with new CustomEvent(), you can create and dispatch custom events.
Syntax
// Fires an event on the element.
element.dispatchEvent(eventObject);
// Creates a custom event.
var event = new CustomEvent("eventName", { detail: data });
// Creates a standard event.
var event = new Event("eventName");
Methods & Constructors
| Method / Constructor | Description |
|---|---|
| dispatchEvent(event) | Fires the specified event object on the HTML element. Any event listeners registered on that element are executed. |
| new Event("eventName") | Creates a standard event object. Use this to manually fire built-in events such as click or input. |
| new CustomEvent("eventName", options) | Creates a custom event. You can include arbitrary data in the detail property of options, which listeners can access via event.detail. |
Sample Code
<button id="btn">Click</button> <button id="autoBtn">Auto Click</button> <div id="app"></div> <p id="output"></p>
var btn = document.querySelector("#btn");
var autoBtn = document.querySelector("#autoBtn");
var app = document.querySelector("#app");
var output = document.querySelector("#output");
// Register a click event listener on the button.
btn.addEventListener("click", function() {
output.textContent = "Button was clicked";
});
// Use dispatchEvent() to manually fire a standard event.
autoBtn.addEventListener("click", function() {
var clickEvent = new Event("click");
btn.dispatchEvent(clickEvent); // Triggers the click listener on btn.
});
// Listen for a custom event and read its data.
app.addEventListener("userLogin", function(e) {
output.textContent = e.detail.name + " has logged in";
});
// Fire the custom event with data in the detail property.
var loginEvent = new CustomEvent("userLogin", {
detail: { name: "Taro", role: "admin" }
});
app.dispatchEvent(loginEvent);
Overview
element.dispatchEvent() is a method that fires an event programmatically. Because it can trigger event listeners without any user interaction, it is useful for test automation and communication between components.
Using new CustomEvent(), you can define your own event name and include arbitrary data in the detail property. Listeners can then read that data via event.detail, making it a handy mechanism for passing data between HTML elements.
Events fired by element.dispatchEvent() only trigger listeners registered with element.addEventListener(). The browser's default behavior is not triggered — for example, firing a click event on a link will not navigate the page. To enable bubbling, pass { bubbles: true } in the options.
Browser Compatibility
3 or earlier ×
1 or earlier ×
3 or earlier ×
5 or earlier ×
8 or earlier ×
Android Browser
37+ ○
3 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.