I needed to capture the (x, y) coordinates of the user's mouse when they clicked links in a grid. The original code used the clientX and clientY event properties, which worked fine until the grid grew enough rows that the page had to scroll. At that point those values were no longer relative to the position of the document.
The most useful reference I found on the topic was Peter-Paul Koch's write-up on event properties at QuirksMode.
The code I ended up with:
// determine x,y coordinates of mouse position relative to document
var clientX = 0;
var clientY = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY)
{
clientX = e.pageX;
clientY = e.pageY;
}
else if (e.clientX || e.clientY)
{
clientX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
clientY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
One note from the present day: pageX and pageY are supported everywhere now, so the fallback branch is only there for very old versions of Internet Explorer and can be dropped from new code.