javascript, mouse position on an element

0

To know the position of the mouse in a elm.onmouseover(mouse) use element, but you can not use this if it is already on top of that element, and elm.onmousemove(mouse) , you would have to move the mouse, like get the mouse position in relation to an element when it is already on top of it without using elm.onmousemove() ?

    
asked by anonymous 30.07.2017 / 00:17

1 answer

1

If the mouse may not have moved, you can use the mouseenter to get the initial coordinates, then keep updating the coordinates with onmousemove as you are already doing.

var x = null;
var y = null;

document.addEventListener('mousemove', onMouseUpdate, false);
document.addEventListener('mouseenter', onMouseUpdate, false);

function onMouseUpdate(e) {
    x = e.pageX;
    y = e.pageY;
}

This event triggers the page load, so even if the mouse does not move, the coordinates are already available in the x and y variables.

Example taken from this response from SOen

    
01.08.2017 / 03:20