Get the Current Cursor Position with JavaScript

10/16/2021
Contents
In this article, you will learn how to get the current cursor position with JavaScript.
MouseEvent.clientX/clientY
To get the current cursor position, you can use the JavaScript MouseEvent.clientX and MouseEvent.clientY property.
The MouseEvent.clientX/clientY property returns the horizontal/vertical coordinate within the application’s viewport at which the event occurred.
let x = event.clientX;
let y = event.clientY;
Demo
You can get the cursor position by moving the cursor within the demo range (the origin is at the top left of the demo range).
Code
HTML
<p class="position">
X: <span id="x"></span><br>
Y: <span id="y"></span>
</p>
JavaScript
window.addEventListener('mousemove', (event) => {
let x = event.clientX;
let y = event.clientY;
document.getElementById('x').innerHTML = x;
document.getElementById('y').innerHTML = y;
});