Maintain vertical scroll position

More...

This post describes how to maintain vertical scroll position after form submission or clicking on the link. Script will read vertical scroll position and append scroll value to the URL. After page is loaded, JavaScript function will search for the scroll parameter in the URL and set the scroll position.

Demo first. Please try to scroll few lines down and click on the myScroll() link. Reloaded page should stay at the same vertical position. VoilĂ ! And the source:

// define functions
var setScroll,
    myScroll;

// if query string in URL contains scroll=nnn, then scroll position will be restored
setScroll = function () {
    // get query string parameter with "?"
    var search = window.location.search,
        matches;
    // if query string exists
    if (search) {
        // find scroll parameter in query string
        matches = /scroll=(\d+)/.exec(search);
        // jump to the scroll position if scroll parameter exists
        if (matches) {
            window.scrollTo(0, matches[1]);
        }
    }
};

// function appends scroll parameter to the URL or returns scroll value
myScroll = function (url) {
    var scroll, q;
    // Netscape compliant
    if (typeof(window.pageYOffset) === 'number') {
        scroll = window.pageYOffset;
    }
    // DOM compliant
    else if (document.body && document.body.scrollTop) {
        scroll = document.body.scrollTop;
    }
    // IE6 standards compliant mode
    else if (document.documentElement && document.documentElement.scrollTop) {
        scroll = document.documentElement.scrollTop;
    }
    // needed for IE6 (when vertical scroll bar is on the top)
    else {
        scroll = 0;
    }
    // if input parameter does not exist then return scroll value
    if (url === undefined) {
        return scroll;
    }
    // else append scroll parameter to the URL
    else {
        // set "?" or "&" before scroll parameter
        q = url.indexOf('?') === -1 ? '?' : '&';
        // refresh page with scroll position parameter
        window.location.href = url + q + 'scroll=' + scroll;
    }
};

// add onload event listener
if (window.addEventListener) {
    window.addEventListener('load', setScroll, false);
}
else if (window.attachEvent) {
    window.attachEvent('onload', setScroll);
}

The link myScroll() shows how to call this page with some parameters and maintain scroll position. After clicking on the link, you will see example parameters followed by scroll position parameter. Please try to change scroll value directly in the address line and press enter. Page should take vertical position according to the changed value.

You can save this functions to the redips-scroll.js file and include it to the pages where maintaining vertical scroll position is important.

This entry was posted on November 16, 2009 and is filed under JavaScript

Related posts

33 Responses to Maintain vertical scroll position

  1. Pingback: how to save and set window.pageYOffset with shadowbox.js | DIGG LINK

  2. sam says:

    This script is awesome, exactly what I was looking for... keep it up!!!!

  3. Tom says:

    Looks great.

    Can this be adapted to work on a div on a page?

  4. dbunic says:

    Yes, myScroll() function can be called from DIV onClick event also.

  5. jan says:

    boy, that was easy, thank you! :)

  6. ken says:

    Your example with a form uses two PHP scripts. I have a single PHP script that generates a form. When the form is submitted the script calls itself - the variables are POSTed. I know PHP, but not so much javascript. I've been able to get the current Y position and pass it to the PHP script. After submission when the script runs, it will display the PHP variable, but I have not been able to figure out how to modify the set_scroll function to read that PHP variable and use it to position the page. Would you mind providing an example or some suggestions? Thanks!

  7. dbunic says:

    @ken - This demo doesn't use PHP or any other server side scripts. It's completely client side solution and server independent. JavaScript setScroll() function is called after page is loaded. Inside that function you will see the code where it searches for scroll parameter and sets vertical scroll position.

    So, when form is posted to the server, it is important to send scroll parameter as well and send it back in URL. This will allow setScroll() to read query string and to return scroll position.

  8. Lee says:

    Hey guys awesome script just what i need, however i have a question, when adding the javascript to the link is there a way to hide the ?param1=a&param2=b&param3=c&scroll=942

    so that it displays the original url?

  9. dbunic says:

    @Lee - After page is loaded, setScroll() should be able to read scroll position from somewhere - for example, it can be hided inside page JavaScript section. This modification will need some server side tasks to read scroll position and to dynamically change/generate JavaScript code. Originally, JS code presented on this post reads "scroll" position from URL (window.location.search) and it completely independent from the server side. So answer to your question is "Yes", it possible to hide, but then you will need to involve server side scripting.

  10. umer drys says:

    LOL why does most people not add the java start and stop code to the code so we have to fiddle with it millions of times?

  11. umer drys says:

    the code dont work in IE10

  12. Benley says:

    You can't expect a user to click a link just so they can remember the scroll position.

    It's supposed to remember scroll position while the user is scrolling.

  13. dbunic says:

    @Benley - I can agree with you, but idea of this JS code is to remember vertical scroll position after user made some action (like click on a link). This was useful for our internal Web application and my intention was to share the code. Yes it's possible to improve the script and to set onScroll() event listener but I didn't want to import addition logic and to extend this script. This way, concept should be easy to understand and adjustable for other scenarios.

    Anyway, thank you for your comment.

Leave a Reply

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

*

In case of posting HTML tags or JavaScript code please convert special characters to HTML entities.
Especially pay attention to convert "<" character to "&lt;" entity!