Sometimes, we want to get x and y coordinates on mouse click with JavaScript.
In this article, we’ll look at how to get x and y coordinates on mouse click with JavaScript.
How to get x and y coordinates on mouse click with JavaScript?
To get x and y coordinates on mouse click with JavaScript, we can get the clientX
and clientY
properties from the mouse event object.
For instance, we write
const printMousePos = (event) => {
const { clientX, clientY } = event;
document.body.textContent = `${clientX}, ${clientY}`;
};
document.addEventListener("click", printMousePos);
to call addEventListener
to add a click listener to the page.
printMousePos
is called when we click on anything on the page.
Then we get the x and y coordinates of the mouse with clientX
and clientY
respectively.
Conclusion
To get x and y coordinates on mouse click with JavaScript, we can get the clientX
and clientY
properties from the mouse event object.