Getting location of mouse click, where the element clicked on is the reference point

Viewed 39

I would like to get the coordinates of every mouse click, and have the element's beginning as the reference point (so click at the first top-left pixel will be 0,0).

I know functions such as pageX/Y and clientX/Y, but they use a different reference point.

1 Answers

you can do it by applying this little trick : you get the pageX and pageY coordinates and then you sub the element offset coordinates (which is how far the element is from the pageX/pageY) and you can choose any element you want to be the reference point for this example we have the <div id="test"></div>

var testDiv = document.getElementById("test")
testDiv.addEventListener("click",function(e){
 var crd = {x :0,y:0};
 crd.x = e.pageX - testDiv.offsetLeft
 crd.y = e.pageY - testDiv.offsetTop
 console.log(crd)
})
* {
margin:0;
padding:0;
box-sizing : border-box;
}

#test{
margin: 60px;
width : 200px;
height : 200px;
border : 2px solid black;

}
<div id="test"></div>

Related