Get mouse coordinates for a specific element

2

I created a chart where I move objects with the mouse. I wanted to get the actual coordinates defined in the chart. I'm just getting the x and y positions of the window coordinates. On my axis I define the maximum and minimum of x, and if the object is in the middle of the axis, get for example half of the maximum. The x-axis is 400px in size. How can I get the real coordinates?

    
asked by anonymous 10.12.2014 / 12:02

1 answer

3

In event% with% of a given element, you get the coordinates of the cursor relative to the window with the mousemove faults and clientX tails properties of the event:

elemento.onmousemove = function(e) {
    // coordenadas em e.clientX e e.clientY
}

To calculate the coordinate relative to the element itself, or to some other, you first need to find out the position of the element in the window. You can do this with clientY of the element:

var boxDoElemento = elemento.getBoundingClientRect();
alert(boxDoElemento.left); // posição x
alert(boxDoElemento.top);  // posição y

If there is no page rolling, just subtract the position of the mouse cursor position element to get the relative position. If there is a bearing, you need to discount it.

Putting everything together to get what you want, considering an element in an arbitrary position of the screen (the red border):

var elemento = document.querySelector('#meuElemento');
var boxDoElemento = elemento.getBoundingClientRect();

elemento.onmousemove = function(e) {
    var rolamentoX = document.body.scrollLeft;
    var rolamentoY = document.body.scrollTop;
    var posX = e.clientX - boxDoElemento.left + rolamentoX;
    var posY = e.clientY - boxDoElemento.top + rolamentoY;
    elemento.innerHTML = posX + ', ' + posY;
}
#meuElemento {
  width: 50%;
  height: 250px;
  margin-left: 25%;
  margin-top: 100px;
  border: 1px solid red;
}
<div id="meuElemento">passe o mouse aqui dentro</div>
    
10.12.2014 / 12:56