How do I get the absolute position of a mouse click from an onClick event on the body?
The commenter is correct. pageX and pageY give you the mouse position relative to the entire document not its parent div. But if you're interested you can get the position relative to the document from the position relative to a div.
Get the position of the parent div relative to the body, then add the two values.
x = parentdiv.style.left + e.pageX;
y = parentdiv.style.top + e.pageY;
(0,0)
_____________________
|
|
| __________
|----100----| |
| |---60---* |
| |__________|
|
|
* = Mouse Pointer
I made the diagram because it was fun. Not because I felt you needed one!!
Also, for the above to work you may need to parseInt.
According to this (http://docs.jquery.com/Tutorials:Mouse_Position), those should give you absolute positions. offsetX/Y
gives you the relative position.
Edit November 2013: the original "Mouse Position" link seems to be broken, but the documentation for pageX
contains an example that utilizes jQuery pageX
/Y
. The page about the offset
method also contains relevant examples.
If I understood your question well this would be the solution
$("body").click(function(e){
var parentOffset = $(this).offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
window.alert(relX);
window.alert(relY);
});