Wednesday, May 5, 2010

Capturing mouse position with JavaScript

I had an issue today where I needed to capture the (x, y) coordinates of the user's mouse when they clicked on various links in a grid. The original code was using the clientX and clientY event properties to determine the coordinates, which seemed to work well; however, when the grid contained several more rows of data the page required scrolling and the clientX and clientY values were no longer relative to the position of the page.
Google had quite  few articles on the topic, but the one I ended up finding the most useful was:
The code I ended up using in my scenario was:

// 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;