Monday, June 3, 2024
12
rated 0 times [  15] [ 3]  / answers: 1 / hits: 27365  / 14 Years ago, sat, april 10, 2010, 12:00:00

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.


More From » mouse-position

 Answers
15

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.


[#97113] Wednesday, April 7, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennanm

Total Points: 510
Total Questions: 103
Total Answers: 95

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
brennanm questions
Thu, Jan 9, 20, 00:00, 5 Years ago
Thu, Sep 26, 19, 00:00, 5 Years ago
Thu, Aug 29, 19, 00:00, 5 Years ago
;