In this article, we’ll learn multiple ways to easily simulate a mouse click or tap on an element in the HTML DOM, using JavaScript.
Use click()
method
This is the easiest and most basic method to simulate a mouse click on an element. Every HTMLElement
has a click()
method that can be used to simulate clicks on it. It fires the click
event on the element when it is called. The click
event bubbles up to elements higher in the document tree and fires their click
events.
const target = document.querySelector('#target');
target.click();
To use the click()
method, you first need to select the element in JavaScript, using a method like querySelector()
or getElementById()
. You’ll be able to access the HTMLElement
object from the method’s return value, and call the click()
method on it to simulate the click.
Let’s see an example, where we simulate a button click every second, by calling click()
in setInterval()
.
const target = document.querySelector('#target');
let clickCount = 0;
const clickCountEl = document.getElementById('click-count');
clickCountEl.innerText = clickCount;
// Programmatically click button every 1 second
setInterval(() => {
target.click();
clickCount++;
clickCountEl.innerText = clickCount;
}, 1000);
<button id="target">Target</button>
<br /><br />
Clicks: <span id="click-count"></span>
Result
Notice how there are no visual indicators of a click occurring because it’s a programmatic click.
Since click()
causes the click
event to fire on the element, any click
event listeners you attach to the element will be invoked from a click()
call.
In the following example, we use a click
event listener (instead of setInterval
) to increase the click count, and another listener to toggle the button’s style when clicked.
const target = document.querySelector('#target');
let clickCount = 0;
const clickCountEl = document.getElementById('click-count');
clickCountEl.innerText = clickCount;
target.addEventListener('click', () => {
clickCount++;
clickCountEl.innerText = clickCount;
});
target.addEventListener('click', () => {
target.classList.toggle('btn-style');
});
setInterval(() => {
target.click();
}, 1000);
<button id="target">Target</button>
<br /><br />
Count: <span id="click-count"></span>
.btn-style {
color: white;
background-color: blue;
border-radius: 2px;
}
Simulate mouse click with MouseEvent
object
Alternatively, we can use a custom MouseEvent
object to simulate a mouse click in JavaScript.
const targetButton = document.getElementById('target');
const clickEvent = new MouseEvent('click');
targetButton.dispatchEvent(clickEvent);
The MouseEvent
interface represents events that occur from the user interacting with a pointing device like the mouse. It can represent common events like click
, dblclick
, mouseup
, and mousedown
.
After selecting the HTMLElement
and creating a MouseEvent
, we call the dispatchEvent()
method on the element to fire the event on the element.
For example:
const clickEvent = new MouseEvent('click');
const targetButton = document.getElementById('target');
let clickCount = 0;
const clickCountEl = document.getElementById('click-count');
clickCountEl.innerText = clickCount;
targetButton.addEventListener('click', () => {
clickCount++;
clickCountEl.innerText = clickCount;
});
setInterval(() => {
const clickEvent = new MouseEvent('click');
targetButton.dispatchEvent(clickEvent);
}, 1000);
<button id="target">Target</button>
<br /><br />
Clicks: <span id="click-count"></span>
Any click
event listener attached to the element is called with the MouseEvent
object that was passed to dispatchEvent()
.
const clickEvent = new MouseEvent('click');
const targetButton = document.getElementById('target');
targetButton.addEventListener('click', (event) => {
console.log(clickEvent === event); // true
});
targetButton.addEventListener('click', (event) => {
console.log(clickEvent === event); // true
});
targetButton.dispatchEvent(clickEvent);
Result
Apart from the event type passed as the first argument, we can pass options to the MouseEvent()
constructor to control specific details about the event:
const targetButton = document.getElementById('target');
const clickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: false,
view: window
});
targetButton.dispatchEvent(clickEvent);
The bubbles
property determines whether the event can bubble up the DOM tree to the element’s containing elements.
The cancelable
property determines whether or not the event’s default action can be prevented.
The view
property sets the event’s AbstractView. You should pass the window
object here.
Find more options in the MDN documentation for the MouseEvent()
constructor and the now deprecated MouseEvent.initMouseEvent()
method.
Simulate mouse click at position
We can also simulate a mouse click on an element at a specific position on the visible part of the webpage.
We do this by selecting the element with the document.elementFromPoint()
method, and then simulating the click with the click()
method.
const targetButton = document.elementFromPoint(x, y).click();
targetButton.click();
The elementFromPoint()
method returns the topmost element at the specified coordinates, relative to the browser’s viewport. It returns an HTMLElement
, which we call click()
on to simulate the mouse click from JavaScript.
In the following example, we have a button and a containing div
:
<div id="container">
<button id="target">Target</button>
<br /><br />
Count: <span id="click-count"></span>
</div>
Using CSS, we position the #container
div
to make its top-left corner exactly at the position (200, 100)
in the viewport.
#container {
position: absolute;
top: 100px;
left: 200px;
height: 100px;
width: 100px;
border: 1px solid black;
}
The #target
button is at point (0, 0)
in its #container
, so point (200, 100)
in the viewport.
To get the position of the #target
with more certainty, we add an offset of 10px
each to get the final position to search for: (210, 110)
.
let clickCount = 0;
const clickCountEl = document.getElementById('click-count');
clickCountEl.innerText = clickCount;
const targetButton = document.getElementById('target');
targetButton.addEventListener('click', () => {
clickCount++;
clickCountEl.innerText = clickCount;
});
// Offset of 10px to get button's position in container
const x = 200 + 10;
const y = 100 + 10;
setInterval(() => {
const buttonAtPoint = document.elementFromPoint(x, y);
buttonAtPoint.click();
}, 1000);
To verify that we’re actually selected the button by its position and it’s getting clicks, we select it by its ID (target) and set a click event listener on the HTMLElement
returned, which will increase the count of how many times it has been clicked.
And we’re successful:
Simulate mouse click at position with MouseEvent
object
We can also simulate a mouse click on an element at a certain (x, y)
position using a MouseEvent
object and the dispatchEvent()
method.
Here’s how:
const clickEvent = new MouseEvent('click', {
view: window,
screenX: x,
screenY: y,
});
const elementAtPoint = document.elementFromPoint(x, y);
elementAtPoint.dispatchEvent(clickEvent);
This time we specify the screenX
and screenY
options when creating the MouseEvent
.
screenX
sets the position where the click
event should occur on the x-axis. It sets the value of the MouseEvent
‘s screenX
property.
screenY
sets the position where the click
event should occur on the Y-axis. It sets the value of the MouseEvent
‘s screenY
property.
So we can use MouseEvent
to replace the click()
method in our last example:
// ...
// Offset of 10px to get button's position in container
const x = 200 + 10;
const y = 100 + 10;
setInterval(() => {
const buttonAtPoint = document.elementFromPoint(x, y);
const clickEvent = new MouseEvent('click', {
view: window,
screenX: x,
screenY: y,
});
buttonAtPoint.dispatchEvent(clickEvent);
}, 1000);
Note: screenX
and screenY
doesn’t decide where the click should occur (elementFromPoint
does). These options are set so that they can be accessed from any click
event listener attached to the element at the point.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.