Javascript: Get mouse position relative to parent element

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.


jquery offset() method handles parent positioning, so

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

is plain browser abstracted jquery.