JavaScript Cursor Position
I discovered that IE’s clientX and clientY measurements were sometimes a couple pixels out. It turns out this is because IE’s clientX and clientY measurements start from (2,2) in standards mode, and (0,0) in quirks mode.
Get Beau Hartshorne’s stories in your inbox
Join Medium for free to get updates from this writer.
IE stores this offset in its document.documentElement.clientLeft and document.documentElement.clientTop properties. This code should calculate the correct cursor position in all current browsers:
function getPosition(e) {
e = e || window.event;
var cursor = {x:0, y:0};
if (e.pageX || e.pageY) {
cursor.x = e.pageX;
cursor.y = e.pageY;
} else {
var de = document.documentElement;
var b = document.body;
cursor.x = e.clientX +
(de.scrollLeft || b.scrollLeft) -
(de.clientLeft || 0);
cursor.y = e.clientY +
(de.scrollTop || b.scrollTop) -
(de.clientTop || 0);
}
return cursor;
}Originally published at hartshorne.ca on January 23, 2006.







