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>