Get exact relative mouse position X Y

14,405

More examples here: show-popup-on-mouse-location


Mouse coordinates within element

The most accurate way to get the mouse coordinates within an element (without scrollbars) relative to viewport is by calculating the difference between

const getMousePos = (evt) => {
  const pos = evt.currentTarget.getBoundingClientRect();
  return {
    x: evt.clientX - pos.left,
    y: evt.clientY - pos.top
  };
};

document.querySelector("#target").addEventListener('mousemove', (evt) => {
  const mPos = getMousePos(evt);
  evt.currentTarget.textContent = `Mouse position x:${mPos.x}  y:${mPos.y}`;
});
#target {
  position: absolute;
  left: 50px;
  top: 20px;
  width: 200px;
  height: 100px;
  background: #0bf;
  transform: translate(20px, 30px); /* works even with translate */
}
<div id="target"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Subtracting those values you can retrieve the exact mouse position, x:0, y:0 being the upper left corner of your element. Even if an element is CSS-transformed, i.e: transform: translate(-50%, -50%), the returned values are still correct.

Share:
14,405
Mediator
Author by

Mediator

I'm owner kitesurfing schools, lessons and equipment website.

Updated on June 12, 2022

Comments

  • Mediator
    Mediator almost 2 years

    I create table, handlers hooked up mousemove. But in top left point I get .offsetX.offsetY equals -5-5. Why? I need 0\0.

    <table cellpadding="0" 
           id="target" 
           cellspacing="0"
           width="602" 
           height="500"  
           style="float:left;
                  position:relative;
                  background: url(/content/games/kamikaze2/back.jpg) no-repeat 0 0;">
        <tbody>...
    </tbody>
    </table>
    
    <script type="text/javascript">
    
        $("#target").mousemove(function (event) {
            var msg = "Handler for .mousemove() called at ";
            msg += event.offsetX + ", " + event.offsetY;
            $("#log").append("<div>" + msg + "</div>");
        });
    </script>