14

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,738
  • 10
  • 38
  • 42
Peterim
  • 989
  • 4
  • 15
  • 25

3 Answers3

29

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
  • 61,328
  • 9
  • 119
  • 152
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
  • 8,887
  • 6
  • 48
  • 79
0

Try the offsetParent property.

Try this:

positionX = document.getElementByID('childId').offsetParent.offsetLeft;
positionY = document.getElementByID('childId').offsetParent.offsetLeft;
Satpal
  • 129,808
  • 12
  • 152
  • 166
Joshua Enfield
  • 16,662
  • 9
  • 48
  • 94