Thursday, July 8, 2010

Cross-browser Mouse Coordinates

Embarassing as it is, it took me days (weeks?) to get a javascript tooltip working. The concept was sound, it should have been easy, but I was swamped by problems like the div flickering, appearing way below the mouse, and the positioning just not working across browsers. The first problem was solved by simply making the tooltip appear a few pixels above and to the left of the mouse pointer, because I discovered displaying it with the same coordinates of the mouse will trigger onmouseover and onmouseout in an infinite loop.

The last two problems involve browser compatibility, which I solved with this bit of (javascript) code:

function getX(event) //left position
{
if(!event.pageX)
{
return event.clientX;
}
else
{
return event.pageX - (document.body.scrollLeft || document.documentElement.scrollLeft);
}
}

function getY(event) //top position
{
if(event.pageY)
{
return event.pageY - (document.body.scrollTop || document.documentElement.scrollTop);
}
else
{
return event.clientY;
}
}


What these functions do is simply get the position of the mouse (in pixels) relative to the user's window, however much the page is scrolled*. Pretty basic, I know, but I thought it might benefit somebody out there.

* Not tested extensively, but it works in Firefox, IE, Opera, and Chrome.
** I got lots of help from this compatibility table.

No comments:

Post a Comment