JavaScript to Obtain Scroll Distance

JavaScript provided here allows you to determine the distance that a web page has been scrolled vertically or horizontally.

Two sets of properties are available for obtaining the amount a page may have been scrolled: pageXOffset and pageYOffset, or scrollLeft and scrollTop. While pageXOffset and pageYOffset are properties of the window object, scrollLeft and scrollTop are obtained for either document.body or document.documentElement, depending upon whether the document is in standards or quirks mode.

The pageXOffset and pageYOffset properties are supported in Internet Explorer as of version nine.

Function to Determine Scroll Amount

The following function can be used to determine the amount the page has been scrolled. Results are displayed on the right. Scroll the page to see the values updated.

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 dw_getScrollOffsets function returns an object containing x and y properties. Notice the document.compatMode property is used to determine whether the document is in standards or quirks mode. Then scrollLeft and scrollTop are obtained for the appropriate element (body or documentElement).

// example usage
var off =  dw_getScrollOffsets();
alert( off.y );

The dw_getScrollOffsets function is used to assist in determining event coordinates and element coordinates in the page.