Sometimes, we want to trigger a mouse click programmatically with JavaScript.
In this article, we’ll look at how to simulate a mouse click with JavaScript.
Use the MouseEvent Constructor
We can trigger a mouse click event by using the MouseEvent
constructor.
For instance, we can write:
document.body.addEventListener('click', () => console.log('clicked'))
const evt = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
clientX: 20,
});
document.body.dispatchEvent(evt);
We add a click event on document.body
with the addEventListener
method.
Then we create a MouseEvent
instance with 'click'
as the first argument to set the type of mouse event to click.
The 2nd argument is an object that sets some properties for the mouse event.
view
is set to window
so that we trigger the click event on an element within window
.
bubbles
is set to true
to make it propagate from child to parent.
clientX
is the x-coordinate of the mouse click.
Then we call document.body.dispatchEvent
to trigger the click event on the body element.
Now when dispatch
is run, we should see console log log 'clicked'
.
Conclusion
We can simulate a mouse click with JavaScript by creating a MouseEvent
instance.
Then we call dispatchEvent
on the element that we want to trigger the click from to click on the element programmatically.