Get the Current Cursor Position with JavaScript

Web Design & Web Development

In this article, I will introduce 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;
Sponsored links

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).

Sponsored links

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;
});