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 =;
  // 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

For example:

<div id="paintarea"></div>
'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

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)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.