I will share the most bulletproof mouse code I have created so far. It works on all browsers, it will have all kinds of additions, fields, borders and add-ons (for example, the top panel of stumbleupon).
// Creates an object with x and y defined, // set to the mouse position relative to the state canvas // If you wanna be super-correct this can be tricky, // we have to worry about padding and borders // takes an event and a reference to the canvas function getMouse = function(e, canvas) { var element = canvas, offsetX = 0, offsetY = 0, mx, my; // Compute the total offset. It possible to cache this if you want if (element.offsetParent !== undefined) { do { offsetX += element.offsetLeft; offsetY += element.offsetTop; } while ((element = element.offsetParent)); } // Add padding and border style widths to offset // Also add the <html> offsets in case there a position:fixed bar (like the stumbleupon bar) // This part is not strictly necessary, it depends on your styling offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft; offsetY += stylePaddingTop + styleBorderTop + htmlTop; mx = e.pageX - offsetX; my = e.pageY - offsetY; // We return a simple javascript object with x and y defined return {x: mx, y: my}; }
You will notice that I use some (optional) variables that are undefined in the function. It:
stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0; stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0; styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0; styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
I would recommend only calculating them once, so they are not in the getMouse function.
Simon Sarris May 4 '12 at 2:25 pm 2012-05-04 14:25
source share