2008-04-10

JavaScript - Absolute Position of an Element

i was in the midst of some HTML coding when i needed to be able to find out the absolute position of an element using JavaScript and HTML DOM. After looking through some online and offline references, and trying out some possibilities, i found that there is no element method or property that would give me the values that i needed. (The element.style.top and element.style.left attributes will only return what has been set beforehand, either through script or CSS, and even so, will only be useful for this purpose if the element.style.position attribute has been set to absolute.)

After some searching on the net, i came across a great piece of code (from QuirksMode.org) that does exactly what i needed:

function findPos(obj)
{
    var curleft = curtop = 0;
    
    if (obj.offsetParent)
    {
        do
        {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}


The site where the code snippet was taken from - QuirksMode.org - provides detailed explanations on why it works that way. To use the function above to, for example, find the absolute position of an element called div, you would just have to call

var pos = findPos(div);

The returned variable, pos, would then be an array whose first element (pos[0]) is the number of pixels between the div element and the left edge of the page, and second variable (pos[1]) is the number of pixels from the top of the page.

0 comments: