DEV Community

Christian Heilmann
Christian Heilmann

Posted on

2

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay