JavaScript - dispatchEvent() method

revision:


Category: EventTarget

The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

Calling dispatchEvent() is the last step to firing an event. The event should have already been created and initialized using an Event() constructor.

Syntax :

        dispatchEvent(event)
    

Parameters:

event : the Event object to dispatch. Its "Event.target" property will be set to the current EventTarget.

Examples:

            <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>
        

Practical examples

example: how to create the click event and fire it on a button
code:
                    <div>
                        <button id="buttonId" onclick="alert('Clicked');">Autoclick</button>
                    </div>
                    <script>
                        let event = new Event("click");
                        buttonId.dispatchEvent(event);
                        
                    </script>
                

example: new mouse event

code:
                    <div>
                        <p id="event-2"></p>
                    </div>
                    <script>
                        let event1 = new MouseEvent("click", {
                            bubbles: true,
                            cancelable: true,
                            clientX: 200,
                            clientY: 200
                        });
                        console.log(event1.clientX); // 200
                        document.getElementById("event-2").innerHTML = "clientX : " + event1.clientX + "<br>" + "clientY : " +event1.clientY;   
                        
                    </script>