Muaz
Muaz

Reputation: 11

How do I get the mouse position of a DOM element that is a child of a relative element?

How to get the mouse position over a DOM element, that is a child of a relative element (in JavaScript)?

Upvotes: 1

Views: 1838

Answers (1)

mbillard
mbillard

Reputation: 38842

Here's the method I use when I want to get the mouse position in an element. It returns the y value in a standard axis (bottom -> top) or in the web axis (top -> bottom).

/*
  Get the position of the mouse event in a standard axis system
  in relation to the given element.

  Standard axis system:
    The origin (0, 0) starts at the bottom-left and increases
    going up for 'y' and right for 'x'.
*/
function GetMousePositionInElement(ev, element)
{
    var offset = element.offset();

    var bottom = offset.top + element.height();

    var x = ev.pageX - offset.left;
    var y = bottom - ev.pageY;

    return { x: x, y: y, y_fromTop: element.height() - y };
}

It requires jQuery.

Upvotes: 1

Related Questions