Search code examples
javascriptonclickpositionabsolute

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


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);
    }
};

Solution

  • 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.