JavaScript EditorFree JavaScript Editor     DHTML Editor 

Main Page Previous Section Next Section

15.5 Auto-Scrolling the Page

NN 4, IE 4

15.5.1 Problem

You want the entire browser page to automatically scroll vertically for the user.

15.5.2 Solution

With their Version 4 releases, Internet Explorer and Netscape Navigator empowered their window objects with a scrollBy( ) method. By invoking it repeatedly through a setInterval( ) call, you can scroll the browser window with no user interaction. The following function and setInterval( ) call do the trick:

function scrollWindow( ) {
    window.scrollBy(0, 1);
function initScroll( ) {
    setInterval("scrollWindow( )", 100);

The initScroll( ) function should be invoked by the onload event handler of the body element.

15.5.3 Discussion

Determining the optimum scroll speed is not easy, and may even dissuade you from employing this application except perhaps in a kiosk environment. Scrolling speed is governed by two variables: the number of pixels of the increment (the second parameter of scrollBy( )) and how often the scrollWindow( ) function is invoked (the interval time specified in the setInterval( ) method call). If the pixel increment is too large, the page jumps in big steps that are difficult for the eye to track for any length of time. The smaller the increment, the better, as shown by the one-pixel jumps in the solution.

Frequency is specified by the nominal number of milliseconds between calls to the scrollWindow( ) function. Too large a number makes the page scroll painfully slowly for moderate reading speeds. Too small a number may lead to more comfortable reading in an ideal environment, but it points out a potential problem beyond your control: repetitive execution of the setInterval( ) method's function does not fire in absolutely uniform intervals. The smaller the interval, the more you see the results in bursts of smooth scrolling followed by brief stuttering.

To check on the progress of the autoscroll through the page, you can read the instantaneous scroll amount (in pixels); however, the syntax varies not only between Netscape and IE, but also between standards-compatible mode and quirks mode in IE 6. For Netscape 6 or later, get the read-only properties window.scrollX and window.scrollY. For older IE versions and IE 6 running in backward-compatible mode, use document.body.scrollLeft and document.body.scrollTop. In the CSS-compatibility mode of IE 6, use document.body.parentElement.scrollLeft and document.body.parentElement.scrollTop. The latter pair reads the scroll values for the entire html element filling the window.

15.5.4 See Also

Recipe 13.12 for an alternative way to scroll content (in a positioned div element) without scrolling the window.

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Checker     DHTML Editor