Getting the cursor position with JavaScript

11.04.2017 • 5478 views

Getting the cursor position with JavaScript

This snippet gives you a fully cross-browser way to calculate the user's cursor position — the x and y coordinates relative to the web page.

The coordinate function

Working out the mouse's X and Y coordinates relative to the document can look like a tricky task: every browser exposes its own properties for it. The function below is fully cross-browser and runs on plain JavaScript, with no dependencies. 

function getPosition(e) {
var posx = 0;
var posy = 0; if (!e) var e = window.event; if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
} return {
x: posx,
y: posy
}
}


How to use it

Using the function is straightforward. To get the coordinates of a click, for example, just pass getPosition into the event handler. In practice it looks roughly like this:

document.addEventListener( "click", function(e) {
var x = getPosition(e).x; // Получаем координаты X
var y = getPosition(e).y; // Получаем координаты Y
console.log("x pos: "+ x +" // y pos:"+ y); // Выведем результат в консоль });


The same approach works with other JavaScript events. We hope the snippet came in useful. If you need more complex interactivity on your site, get in touch — we will suggest the best way to build it.

Need our services?
Leave a request
By submitting the form, you consent to the processing of personal data. We guarantee that your data
will never be passed on to third parties.
Sending...
Telegram
Write us on Telegram We reply within 5 min