[ Team LiB ] Previous Section Next Section

13.8 Determining the Location of a Nonpositioned Element

NN 6, IE 5

13.8.1 Problem

You want to ascertain the pixel coordinates of an element that the browser has placed during normal page flow.

13.8.2 Solution

The following getElementPosition( ) function returns an object with properties for the left and top absolute coordinates of the element whose ID is passed as an argument:

function getElementPosition(elemID) {
    var offsetTrail = document.getElementById(elemID);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

This function is compatible with browsers that support W3C DOM element-referencing syntax.

13.8.3 Discussion

The typical purpose of establishing the absolute location of an element on the page is to position some other element on it or in relation to it. Because the location of inline elements can vary widely with the browser window size and font situation, the values need to be calculated after the page has loaded, is reflowed in response to other dynamic content additions and deletions, or the window is resized.

Although some browser versions report the accurate value simply via the offsetLeft and offsetTop properties of an element, others require the addition of any offsets imposed by parent elements offering positioning contexts (the element indicated by the offsetParent property). Therefore, this function includes a loop that iterates through the offsetParent hierarchy of the element passed as an argument to the function, accumulating additional coordinate offsets if they exist.

This function is not needed for CSS-type absolute-positioned elements because you can obtain the correct coordinates directly via the style.left and style.top properties (or via the effective style property, as retrieved through the script shown in Recipe 11.12).

13.8.4 See Also

Recipe 11.12 for reading initial style properties set in <style> and <link> tags.

    [ Team LiB ] Previous Section Next Section