JavaScript - createEvent() method

revision:


Category : document

The createEvent() method creates an event of the type specified/event object. The returned object should be first initialized and can then be passed to "EventTarget.dispatchEvent".

Syntax :

        document.createEvent(type)
    

Parameters:

type : as tring that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents".

Examples:

            // Create the event.
            const event = document.createEvent("Event");
            // Define that the event name is 'build'.
            event.initEvent("build", true, true);
            // Listen for the event.
            elem.addEventListener(
                "build",
                (e) => {
                    // e.target matches elem
                },
                false
            );
            // Target can be any Element or other EventTarget.
            elem.dispatchEvent(event);
        

Practical examples

example: the createEvent() method allows to simulate events
*

code:
                    <div>
                        <div id="myDiv" style="padding:5vw;background-color:yellow;" onmouseover="this.innerHTML += '*';">*</div>
                        <p><button onclick="simulateFunction(event)">Simulate Mouse Over</button></p>
                    </div>
                    <script>
                        function simulateFunction(event) {
                            const ev = document.createEvent("MouseEvent");
                            ev.initMouseEvent("mouseover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                            document.getElementById("myDiv").dispatchEvent(ev);
                        }
                    </script>
                

example: to illustrate the createEvent() method in HTML.

This is a sample paragraph

code:
                    <div>
                        <p id="create-a" onmouseout="addText()" >This is a sample paragraph</p>
                        <button onclick="eventAdd()">Simulate Mouse Out</button>
                    </div>
                    <style>
                        p#create-a {border: 0.1vw solid blue; background-color: lightblue;}
                    </style>
                    <script>
                        var i=0;
                        function eventAdd() {
                            var x = document.createEvent("MouseEvent");
                            x.initMouseEvent("mouseout", true, true);
                            document.getElementById("create-a").dispatchEvent(x);
                        }
                        function addText(){
                            var txt=document.getElementById("create-a");
                            txt.innerHTML+=" TEXT"+i;
                            i++;
                        }
                    </script>