Using JavaScript to Remember the Scroll Position

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

After much searching and playing with code, I’ve come to find this method to be most effective cross-browser solution to get and set the browsers scrollbar position. It has been tested to work in IE6, IE7, Firefox, Opera, and assumed to work in other popular browsers, as well.

function getScrollXY() {
    var x = 0, y = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        // Netscape
        x = window.pageXOffset;
        y = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        // DOM
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        // IE6 standards compliant mode
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    }
    return [x, y];
}

function setScrollXY(x, y) {
    window.scrollTo(x, y);
}
If you enjoyed this article, please share it with a friend!

3 Responses to Using JavaScript to Remember the Scroll Position

  1. Anthony says:

    The getscrollXY function doesn’t seem to work in IE7.0,
    the values returned is always [0,0]

  2. Cory LaViska says:

    Make sure the scrollbar is not actually at the [0,0] position when you call the function. I just tested it in IE7 version 7.0.5730.11 and it outputs the correct results.

  3. Shaun says:

    It depends on the DOCTYPE in IE7. I had to use documentElement for IE7 because of my doctype. Because body.scrollLeft and body.scrollTop still have values and come out as true using your code. But the values are 0,0 as Anthony stated.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>