Beau Hartshorne

JavaScript Cursor Position

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

I published this in 2006 as I was building Snipshot. This snippet found its way into many popular JavaScript frameworks, and I suggest you use one of them to handle mouse events since they are constantly updated to reflect best practices and new browser implementations.