How to get the absolute position of the mouse click from the onClick event on the body?

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

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

Please note that I can use 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
source share
4 answers

According to this ( http://docs.jquery.com/Tutorials:Mouse_Position ), this should give you absolute positions. offsetX/Ygives you a relative position.

2013 .: " ", , , pageX , jQuery pageX/Y. offset .

+4

. pageX pageY , div. , div.

div , .

x = parentdiv.style.left + e.pageX;
y = parentdiv.style.top + e.pageY;



(0,0)
_____________________
|
|
|            __________
|----100----|          |
|           |---60---* |
|           |__________|
|
|
        * = Mouse Pointer

, . , , !

, parseInt.

+7

The solution referenced by @Mrchief http://docs.jquery.com/Tutorials:Mouse_Position was to link to the document, not the body element.

//binding the function
var methods = {
    init: function () {
        $(document).click(_handleClick);
    }
};
0
source

If I understood your question well, that would be a 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);
});
0
source

All Articles