Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
};
like image 903
Aaron Silverman Avatar asked Jul 08 '11 19:07

Aaron Silverman


4 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)
  }
)
like image 92
Ron Lavit Avatar answered Oct 19 '22 19:10

Ron Lavit


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);
});
like image 24
Arash Abedin Avatar answered Oct 19 '22 18:10

Arash Abedin


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.

like image 34
Tyler Biscoe Avatar answered Oct 19 '22 18:10

Tyler Biscoe


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.

like image 31
Mrchief Avatar answered Oct 19 '22 20:10

Mrchief