Natively this should be done using the dispatchEvent
method of a object EventTarget
. The parameter specified in this method should be an object of type Event
. That is, we first need to create the instance of the event we want to fire; In this case, for example, I'll use events click
and mouseover
.
const click = new Event("click");
const mouseOver = new Event("mouseover");
We look for the target element in the DOM:
const button = document.getElementById("button");
And we trigger the respective events:
button.dispatchEvent(click);
button.dispatchEvent(mouseOver);
See working:
const click = new Event("click");
const mouseOver = new Event("mouseover");
const button = document.getElementById("button");
button.addEventListener("click", function (event) {
alert("Click");
});
button.addEventListener("mouseover", function (event) {
this.style.color = "red";
});
button.dispatchEvent(click);
button.dispatchEvent(mouseOver);
<button id="button">Clique em mim</button>