Get the coordinates of the cursor in JavaScript

This tutorial will show you how to get the coordinates of the cursor in JavaScript.

First of all, let’s create our HTML element which shows us the position coordinates of the cursor in the browser.   X for horizontal coordinates and Y for vertical coordinates.

X: <span id="x-value"></span>
Y: <span id="y-value"></span>

If you run this on your browser, you will be able to see X and Y vertically on the webpage but nothing will happen now. After we add our JavaScript code you can see wherever I move the cursor on the browser it will show you the position coordinates of the cursor.

Now here’s the JavaScript code, the main part of our tutorial.

document.onmousemove = function(e){
   var x = e.clientX; 
   var y = e.clientY;
   document.getElementById('x-value').textContent = x;
   document.getElementById('y-value').textContent = y;

In the above JavaScript code, we have used clientX to get the coordinate horizontally and clientY to get the coordinate vertically of the cursor pointer.

When you move the cursor the clientX and clientY properties return the horizontal and vertical position of the cursor pointer.

To detect mouse movement, we have used the onmousemove event so that whenever we move our mouse, we get the position of the pointer.

Also, read: Move an Element to Mouse Position in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *