JavaScript Cursor Position
January 23, 2006
Update: I submitted this to MochiKit while building Snipshot, a web tool to edit pictures online.
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.
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;
}