There are many examples of using jQuery to get mouse coordinates, but no one fixed my problem.
The body of my webpage is 1000 pixels wide, and I center it in the middle of the user browser window.
body { position:absolute; width:1000px; left: 50%; margin-left:-500px; }
Now, in my JavaScript code, when the user right-clicked on my page, I wanted the div to display at the mouse position.
The problem is that using the e.pageX value was not entirely correct. This will work well if I resize the browser window to a width of about 1000 pixels. Then the pop div will appear in the correct position.
But if you increase the size of my browser window to, say, 1200 pixels wide, the div will appear about 100 pixels to the right of where the user clicked.
The solution is to combine e.pageX with the bounding box of the body element. When a user resizes his browser window, the value of the element on the left of the "body element changes, and we must take this into account:
// Temporary variables to hold the mouse x and y position var tempX = 0; var tempY = 0; jQuery(document).ready(function () { $(document).mousemove(function (e) { var bodyOffsets = document.body.getBoundingClientRect(); tempX = e.pageX - bodyOffsets.left; tempY = e.pageY; }); })
Phew It took me a while to fix this! Hope this is helpful for other developers!
Mike Gledhill Sep 20 '12 at 7:50 2012-09-20 07:50
source share