JavaScript Articles

Buy this website for $5000 USD

Priced to sell, this is an established JavaScript website, growing in popularity as evidenced by its Alex ranking. Includes most website content. The price is NON-NEGOTIABLE. Serious buyers should contact

Obtaining the Scroll Width and Height of a Document

I have yet to see anyone give a complete and accurate description of how to portably obtain the scroll area of a document with JavaScript. In this article, I intend to set the record straight.

Internet Explorer

In Internet Explorer for Macintosh and Internet Explorer for Windows versions below 6.0, the scroll area properties, scrollLeft and scrollTop are accessed through the document.body object.

Starting with Internet Explorer 6.0, the scroll area properties are still available in the document.body object when the document is not in Standards-Compliant Mode

If the document is in Standards-Compliant Mode, the scroll area properties are instead available in the document.documentElement object.

This is appallingly complicated, yet the scroll width and height can be easily and portably obtained for any IE browser, regardless of whether or not the document is in Standards-Compliant Mode, with the following code:

xScroll = document.body.scrollLeft ||
   document.documentElement.scrollLeft;

yScroll = document.body.scrollTop ||
   document.documentElement.scrollTop;

All Other Browsers

Fortunately, the rest of the world of browser vendors are not the renegades that Microsoft is. You can obtain the scroll area with the pageXOffset and pageYOffset properties of the window object, in all non-Explorer browsers, including Safari and Opera.

xScroll = window.pageXOffset;

yScroll = window.pageYOffset;

Cross-Platform Methods

Below are methods for returning the scroll area width and height, that work on all browsers.

function getScrollWidth()
{
   var w = window.pageXOffset ||
           document.body.scrollLeft ||
           document.documentElement.scrollLeft;
           
   return w ? w : 0;
}

function getScrollHeight()
{
   var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;
           
   return h ? h : 0;
}

Written by: Moshe Moskowitz