views:

499

answers:

1

I've seen a dozen of script that can catch the x and y position of an element/object within the page. But i am always having trouble with catching the x and y when the webpage is using margins at the body, or other elements, absolute/relative elements, such like that.

Is there a solution wich provides the exact position, no matter what margins or paddings are used.

:)

+3  A: 

I use following code to move div box to follow cursor in this Web IME site

function xy(x) {
    o = document.getElementById(x);
    var l =o.offsetLeft; var t = o.offsetTop;
    while (o=o.offsetParent)
     l += o.offsetLeft;
    o = document.getElementById(x);
    while (o=o.offsetParent)
     t += o.offsetTop;
    return [l,t];
}

Its return an array [left,top],

S.Mark
Hi Mark, thank you for your code, but when the page have a margin at the body, the position isnt corrent anymore, you got a solution for that?Thanks in advance
Johnny
how about adding `document.body.offsetLeft` and `document.body.offsetTop` to the return values?
S.Mark
This should work fine regardless of body margins. Make sure you're using a Standards Mode doctype though. In Quirks all bets are off.
bobince
Thank you Mark, i will try that one!@Bobince, i do not have any control over the website where this code will be published, this is part of an interactive advertisement.
Johnny