How do I get the absolute position of a mouse click from an onClick event on the body?

Zugwalt picture Zugwalt · Jul 8, 2011 · Viewed 26.1k times · Source

I am trying to get the absolute position (top and left) of a mouse click relative to the browser/body, not any parent elements within the body.

I have a listener bound to the body, but e.pageX and e.pageY are giving me the position relative to a div.

Note that I can leverage jQuery and YUI functions.

Code that currently does not work correctly:

//getting the position
function _handleClick(e) {
    var data = { absX: e.pageX, absY: e.pageY};
    _logClickData(data);
}

//binding the function
var methods = {
    init: function () {
        $("body").click(_handleClick);
    }
};

Answer

Tyler Biscoe picture Tyler Biscoe · Jul 8, 2011

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.