javascript, mouse position in an element

Asked

Viewed 660 times

0

To know the mouse position in an element use elm.onmouseover(mouse), however it is not possible to use this if it is already on top of this element, and elm.onmousemove(mouse), would have to necessarily move the mouse, how to get the mouse position relative to an element when it is already on top of it without using elm.onmousemove()?

  • In your interaction, does the mouse ever move and stop? Or is it necessary to pick up the coordinates even if the mouse has not moved at any time?

  • no, it does not necessarily move... when it moves is quiet, the event "onmousemove" solves the problem... I imagine what you are going to suggest is to rewrite a variable that has an initial value indicating that the mouse is not on top of the element and goes back to that value when the "onmouseleave" event occurs. It’s just that I started doing it right after posting this question. It just doesn’t work when the page clicks with the mouse standing on top.

1 answer

1


If the mouse may not have moved, you can use the event mouseenter to pick up the initial coordinates, then continue 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 fires on the page load, so even if the mouse doesn’t move, the coordinates are already available in the variables x and y.

Example taken from Soen’s reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.