Get position of element by JavaScript

Johnny picture Johnny · Nov 20, 2009 · Viewed 41.7k times · Source

I've seen dozens of scripts 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 which provides the exact position, no matter what margins or paddings are used?

Answer

YOU picture YOU · Nov 20, 2009

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],