views:

82

answers:

2

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

A: 

Here is a good resource for finding the position of an element: http://www.quirksmode.org/js/findpos.html

And from the same site, a resource for finding mouse position: http://www.quirksmode.org/js/events_properties.html#position

That should be all you need.

W_P
+1  A: 

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.

GoodEnough