Categories
JavaScript Answers

How to Simulate a Click by Using x, y Coordinates in JavaScript?

Spread the love

To simulate a click by using x, y coordinates in JavaScript, we can call the document.elementFromPoint with the x and y coordinates to get the element at those coordinates.

Then we call click on the returned element to click it.

For instance, if we have the following HTML:

<div>
  hello world
</div>

Then we can click it by writing:

document.addEventListener('click', (e) => {
  console.log(e.target)
})

const x = 10
const y = 10
document.elementFromPoint(x, y).click();

We set the x and y values to get the element at that point.

Then we call click on it to click it.

Then in the click listener that we added with addEventListener , we should see the element that’s clicked.

We can also dispatch the click event by using the MouseEvent constructor.

For instance, we can write:

document.addEventListener('click', (e) => {
  console.log(e.target)
})

const x = 10
const y = 10

const click = (x, y) => {
  const ev = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true,
    'screenX': x,
    'screenY': y
  });
  const el = document.elementFromPoint(x, y);
  el.dispatchEvent(ev);
}
click(x, y)

We create the click function that clicks the element with coordinates x and y by using the MouseEvent constructor.

We pass in an object that sets the screenX and screenY to set the location of the click.

And then we get the element at the given x and y coordinates with document.elementFromPoint .

Finally, we call dispatchEvent on it with x and y to do the clicking.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Simulate a Click by Using x, y Coordinates in JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *