Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Get mouse position relative to parent element

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.

like image 823
Peterim Avatar asked Apr 10 '10 18:04

Peterim


2 Answers

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.

like image 190
Matti Virkkunen Avatar answered Nov 02 '22 12:11

Matti Virkkunen


jquery offset() method handles parent positioning, so

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

is plain browser abstracted jquery.

like image 23
citykid Avatar answered Nov 02 '22 11:11

citykid