19

Is there any way to get mouse position relative to it's parent element?

Let's say I have a structure:

<div id="parent">
    <span class="dot"></span>
</div>

When I bring my mouse over span element I need to get its position relative to its parent element (<div id="parent">). PageX/ClientX give me position relative to page/client area, so it's not working for me.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Peterim
  • 1,029
  • 4
  • 16
  • 25

4 Answers4

45

Subtract the viewport-relative position of the parent element you can get via getBoundingClientRect() from the mouse position in the event's clientX and clientY to get relative position.

For example:

element.addEventListener("mousedown", function (e) {
    let bounds = parent.getBoundingClientRect();
    let x = e.clientX - bounds.left;
    let y = e.clientY - bounds.top;

    console.log(x, y);
});

Where element is your inner element receiving the event, and parent is your desired reference for the coordinates.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
5

jquery offset() method handles parent positioning, so

function onsomemouseevent(e) {
    var x = e.pageX - $(e.target).offset().left;
}

is plain browser abstracted jquery.

citykid
  • 9,916
  • 10
  • 55
  • 91
2

Here is a React specific example, but I assume the concepts would work even outside React.

onMouseMove={(e) => {
   var x = e.clientX - e.currentTarget.offsetLeft;
   var y = e.clientY - e.currentTarget.offsetTop;

   // Do something with x and y
}}

Also, I found that throttling the mouse move capturing is useful when you're doing a lot of computation. Here's a nice StackOverflow answer that showed how to do that.

Corey P
  • 955
  • 1
  • 14
  • 23
0

Try the offsetParent property.

Try this:

positionX = document.getElementById('childId').offsetParent.offsetLeft;
positionY = document.getElementById('childId').offsetParent.offsetLeft;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98