Natively this should be done through the method dispatchEvent of an object EventTarget. The parameter indicated in this method should be an object of the type Event. That is, first we need to create the instance of the event we want to shoot; in this case, to illustrate, I will use the 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>
The answer looks good, but in the description this
composedand in the example thisview, I think this is a little confusing.– Guilherme Nascimento
@Guilhermenascimento Thank you for the comment. Yes indeed I left as was the example on MDN, but I agree it’s clearer without
view– Isac