Sometimes, we want to track the user’s mouse’s position with JavaScript.
In this article, we’ll look at how to track the user’s mouse’s position with JavaScript.
Get the Mouse’s Position with the clientX and clientY Properties
We can listen to the mousemove
event which is triggered whenever we move the mouse.
Then from the mousemove
event object, we can use the clientX
and clientY
properties to get the x and y coordinate of the mouse cursor on the page.
For instance, we can write:
document.onmousemove = (event) => {
const {
clientX,
clientY
} = event
console.log(clientX, clientY)
}
to log the x and y coordinates of the mouse in pixels.
We set an event handler function as the value of the document.onmousemove
property.
We attach the event listener to document
because we want to listen to the mouse movement on the page.
The method takes the event
parameter, which is the mousemove
event object.
In the event handler function, we get the clientX
and clientY
properties to get the x and y coordinates of the mouse cursor’s location on the page.
We can also attach the event listener with the addEventListener
method.
For instance, we can write:
document.addEventListener('mousemove', (event) => {
const {
clientX,
clientY
} = event
console.log(clientX, clientY)
})
We call addEventListener
with 'mousemove’
to listen to the mousemove
event.
And then we get the x and y coordinates of the mouse cursor the same way.
Now we should see the x and y coordinates of the mouse cursor logged.
Conclusion
We can use the mousemove
event object’s clientX
and clientY
properties to get the x and y coordinates of the mouse cursor on the page in pixels.