Question

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.

Was it helpful?

Solution

Subtract the position of the parent element (offsetLeft; offsetTop) from the mouse position (pageX; pageY) to get relative position. Remember to take offsetParent into account if you have multiple levels of offsets.

For example:

element.addEventListener("mousedown", function (e) {
  let x = e.pageX - parent.offsetLeft;
  let y = e.pageY - parent.offsetTop;

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

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

OTHER TIPS

jquery offset() method handles parent positioning, so

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

is plain browser abstracted jquery.

Try the offsetParent property. http://help.dottoro.com/ljetdvkl.php

Try this: positionX = document.getElementByID('childId').offsetParent.offsetLeft; positionY = document.getElementByID('childId').offsetParent.offsetLeft;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top