Getting position of mouse within a specified element

W

Weston C

Here's something I'm working on: for a click on a given
element, I want to be able capture the x/y coordinates of the mouse --
that is, the mouse coordinates relative to the top left corner of said
element.

So far, here's what I've got:

http://weston.canncentral.org/misc/webgallery/Haven/pie.html
(Code for the function given in this post below).

It seems to work in Gecko-based browsers, and IE/Win.

It breaks badly in Safari, grabbing what is apparently instead the
viewport position of the mouse. Also, on IE/Mac, it breaks if there's
any scrolling done on the page (try resizing the window so that it's
smaller than the sample image, then scrolling down, and then clicking).

Any ideas what I can do to make it work better for the Mac
browsers? Also, any other platforms which you observe it
breaking under?

Thanks,

Weston

function getClickCoordsWithinTarget(event)
{
var coords = { x: 0, y: 0};

if(!event) // then we're in a non-DOM (pro'ly IE) browser
{
event = window.event;
coords.x = event.offsetX;
coords.y = event.offsetY;
}
else // we assume DOM modeled javascript
{
var Element = event.target ;
var CalculatedTotalOffsetLeft = 0;
var CalculatedTotalOffsetTop = 0 ;

while (Element.offsetParent)
{
CalculatedTotalOffsetLeft += Element.offsetLeft;
CalculatedTotalOffsetTop += Element.offsetTop;
Element = Element.offsetParent ;
}

coords.x = event.pageX - CalculatedTotalOffsetLeft;
coords.y = event.pageY - CalculatedTotalOffsetTop;
}

return coords;
}


~==~
http://weston.canncentral.org/
Taking Pictures During Dreams
weston8[at]cann8central.org
(remove eights to mail me)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top