revision:
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".
Deprecated: this feature is no longer recommended
document.createEvent(type)
Parameters:
type : a string that represents the type of event to be created. Possible event types include : AnimationEvent , ClipboardEvent , DragEvent , FocusEvent , HashChangeEvent , InputEvent , KeyboardEvent , MouseEvent , PageTransitionEvent , PopStateEvent , ProgressEvent , StorageEvent , TouchEvent , TransitionEvent , UiEvent , WheelEvent.
// 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);
example: the createEvent() method allows to simulate events
<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
<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>