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

Viewed 30616

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

I guess you can use window.pageXOffset, window.pageYOffset property

document.body.addEventListener('click',(e)=>{
  console.log(e.clientX + window.pageXOffset, event.clientY + window.pageYOffset)
  }
)
Related