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.
Pass4sure is your best choice for any IT certifications because of its high quality. It provides full-scale study materials, including the questions, answers and pinpoint explanations supplied by a group of IT experts. Its considerate & warmhearted service and complete safeguard measures remove all your doubts about the products quality.The Most Popular exams List :JN0-331HP0-D04 642-164 SY0-101 156-215.65 642-845 650-393 640-816 642-426 HP0-D04 646-363 N10-004EC0-350 350-040 642-072 642-373 646-563 642-145 642-736 XK0-002 642-655 JN0-532 640-802 Click Pass4sure to get more information!