Monday, January 23rd, 2006

JavaScript Tip: Cross Browser Cursor Positioning

Category: JavaScript, Tip

<>p>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:

javascript
< view plain text >
  1. function getPosition(e) {
  2.     e = e || window.event;
  3.     var cursor = {x:0, y:0};
  4.     if (e.pageX || e.pageY) {
  5.         cursor.x = e.pageX;
  6.         cursor.y = e.pageY;
  7.     }
  8.     else {
  9.         cursor.x = e.clientX +
  10.             (document.documentElement.scrollLeft ||
  11.             document.body.scrollLeft) -
  12.             document.documentElement.clientLeft;
  13.         cursor.y = e.clientY +
  14.             (document.documentElement.scrollTop ||
  15.             document.body.scrollTop) -
  16.             document.documentElement.clientTop;
  17.     }
  18.     return cursor;
  19. }

Related Content:

Posted by Dion Almaer at 12:28 am
8 Comments

+++--
3.6 rating from 75 votes

8 Comments »

Comments feed TrackBack URI

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.

Comment by Tom — January 23, 2006

Thanks Tom, I’ve fixed this on my blog.

Comment by Beau Hartshorne — January 23, 2006

Thanks Tom, I fixed this on the blog entry.

Comment by Beau Hartshorne — January 23, 2006

I think this is because of the different box models between quirks and strict modes. The viewport border is 2px wide.

Comment by David — January 23, 2006

Thats a great snippet. I was looking for this for a long time.

Comment by Hasin Hayder — January 23, 2006

helo………

Comment by hendra — May 19, 2006

I usually remove the viewport border in IE by:

html {
border: 0;
}

Does this remove the 2px offset as well?

Comment by Klaus Hartl — September 6, 2007

No, unfortunately border zero has no effect.

Comment by steida — August 24, 2008

Leave a comment

You must be logged in to post a comment.