Sometimes, we want to simulate a click by using x, y coordinates in JavaScript.
In this article, we’ll look at how to simulate a click by using x, y coordinates in JavaScript.
How to simulate a click by using x, y coordinates in JavaScript?
To simulate a click by using x, y coordinates in JavaScript, we can call the initMouseEvent
method.
For instance, we write
const click = (x, y) => {
const ev = document.createEvent("MouseEvent");
const el = document.elementFromPoint(x, y);
ev.initMouseEvent(
"click",
true /* bubble */,
true /* cancelable */,
window,
null,
x,
y,
0,
0 /* coordinates */,
false,
false,
false,
false /* modifier keys */,
0 /*left*/,
null
);
el.dispatchEvent(ev);
};
to create the mouse event object by calling the createElement
method with 'MouseEvent'
.
Then we call elementFromPoint
to get the element that we want to click on with the x
and y
coordinates of the screen.
Next we call initMouseEvent
with a few arguments to initialize the mouse event.
'click'
triggers a click.
Then we call it with other arguments to set some options described in the comments.
Finally, we call dispatchEvent
to trigger the mouse event.
Conclusion
To simulate a click by using x, y coordinates in JavaScript, we can call the initMouseEvent
method.