DEV Community

Christian Heilmann
Christian Heilmann

Posted on

Quick solution: getting the mouse position on an element regardless of positioning

Cat with mousepointer on its nose

As I was upgrading an older codebase of mine that used layerX and layerY (boo, non-standard) I looked into a very succinct way of finding the current mouse position on any element regardless of its position, scrolling, padding, margin and such and I found this to work for me, so maybe it is good for you, too.

const getposition = ev => {
  // get the current mouse position in the browser
  let x = ev.clientX;
  let y = ev.clientY;
  // get the position of the element you applied the handler to
  let pos = ev.target.getBoundingClientRect();
  // subtract the position of the element (rounded up to the next
  // integer) from the mouse position and return it.
  return {
    x: x - pos.x|1,
    y: y - pos.y|1
  };
}
Enter fullscreen mode Exit fullscreen mode

For example:

<div id="paintarea"></div>
Enter fullscreen mode Exit fullscreen mode
document.querySelector('#paintarea').addEventListener(
'mousemove', ev => 
{
  let pos = getposition(ev);
  // pos.x is now the x position in the paintarea
  // pos.y is now the y position in the paintarea
});
Enter fullscreen mode Exit fullscreen mode

Here's a codepen of it in action, and you can play with it and give it more annoying things to deal with.

Top comments (0)