JavaScript to Determine Element Coordinates

JavaScript provided here enables to you to determine the position in the document of an HTML element. Our function for obtaining element coordinates will use the getBoundingClientRect method which was introduced by Internet Explorer 5. This method has been adopted by other browsers and is now being standardized.[1] Although the method is quite broadly supported, the proposed function will include the old-fashioned approach for any browsers that don't support it.

Function to Obtain Element Coordinates

Pass a reference to an element as an argument to the following function to obtain its coordinates in the page. A div element to the right demonstrates the result.

function dw_getPageOffsets(el) {
    var sOff = dw_getScrollOffsets(), left = 0, top = 0, props;
    if ( el.getBoundingClientRect ) {
        props = el.getBoundingClientRect();
        left = props.left + sOff.x;
        top = + sOff.y;
    } else { // for older browsers
        do {
            left += el.offsetLeft;
            top += el.offsetTop;
        } while ( (el = el.offsetParent) );
    return { x: Math.round(left), y: Math.round(top) };

function dw_getScrollOffsets() {
    var doc = document, w = window;
    var x, y, docEl;
    if ( typeof w.pageYOffset === 'number' ) {
        x = w.pageXOffset;
        y = w.pageYOffset;
    } else {
        docEl = (doc.compatMode && doc.compatMode === 'CSS1Compat')?
                doc.documentElement: doc.body;
        x = docEl.scrollLeft;
        y = docEl.scrollTop;
    return {x:x, y:y};

Function Explanation and Usage

The getBoundingClientRect method returns an object with the properties left, top, bottom, right, width, and height. Our function makes use of left and top to return an object with x and y properties.

Since the getBoundingClientRect method returns coordinates in the viewport, we add scroll amounts since we are usually looking for coordinates in the document.

The code checks for browser support of the getBoundingClientRect method using object detection. For browsers lacking support, a for loop is used to obtain offsets for the element and its containing elements.

// example usage:
var el = document.getElementById('display');
var loc = dw_getPageOffsets(el);