Monday, January 23rd, 2006
JavaScript Tip: Cross Browser Cursor Positioning
Beau Hartshorne has been burnt by a few pixels when getting the position of the users cursor cross browser.
I discovered that IE’s clientX and clientY measurements were sometimes a couple pixels out. It turns out this is because IE’s the 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 {
-
cursor.x = e.clientX +
-
(document.documentElement.scrollLeft ||
-
document.body.scrollLeft) -
-
document.documentElement.clientLeft;
-
cursor.y = e.clientY +
-
(document.documentElement.scrollTop ||
-
document.body.scrollTop) -
-
document.documentElement.clientTop;
-
}
-
return cursor;
-
}
-












They should try this for line 3 instead:
var cursor = {x:0, y:0};The spontaneous generation of globals has got to be one of the most annoying things about JavaScript.
Anyway, thanks for the tip/link on cursor positioning.
Thanks Tom, I’ve fixed this on my blog.
Thanks Tom, I fixed this on the blog entry.
I think this is because of the different box models between quirks and strict modes. The viewport border is 2px wide.
Thats a great snippet. I was looking for this for a long time.
helo………
I usually remove the viewport border in IE by:
html {
border: 0;
}
Does this remove the 2px offset as well?
No, unfortunately border zero has no effect.