Categories
JavaScript Answers

How to simulate a mouse click using JavaScript?

Spread the love

Sometimes, we want to simulate a mouse click using JavaScript.

In this article, we’ll look at how to simulate a mouse click using JavaScript.

How to simulate a mouse click using JavaScript?

To simulate a mouse click using JavaScript, we can use the MouseEvent constructor.

For instance, we write

const evt = new MouseEvent("click", {
  view: window,
  bubbles: true,
  cancelable: true,
  clientX: 20,
  //...
});
targetElement.dispatchEvent(evt);

to create a MouseEvent object with 'click' and an object with the event object options.

We set the view to the page where the mouse event is triggered.

Also, we set whether the event bubbles and if it’s cancelable.

We can also set the location of the click.

Then we trigger the event with

targetElement.dispatchEvent(evt);

from the targetElement element.

Conclusion

To simulate a mouse click using JavaScript, we can use the MouseEvent constructor.

By John Au-Yeung

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

Leave a Reply

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