Maintain vertical scroll position

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.

39 thoughts on “Maintain vertical scroll position”

  1. Can this be applied to the auto-refresh function of a web page, I am looking for something very similar to this, but it has to work with the auto refresh.

    Cheers

  2. set_scroll() function doesn’t have to be modified. onload event will first set scroll position and set timer to call my_refresh() function (after 2 seconds in this example). my_refresh() is modified my_scroll()

    Hope this will help.
    Bye!

    // onLoad event
    window.onload = function() {
        set_scroll();
        setTimeout(my_refresh, 2000);
    }
    
    // set href location with scroll position
    function my_refresh(){
        var scroll, href, 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;
        }
        // define href
        href = window.location.href;
        // cut out scroll parameter with ? or & before 
        href = href.replace(/.scroll=\d+/g, '')
        // test if href parameter contains ? character
        if (href.indexOf('?') === -1) q = '?';
        else q = '&';
        // refresh page with scroll position parameter
        window.location.href = href + q + 'scroll=' + scroll;
    }
    
  3. I cannot get it to work!!! What do I need to do exactly after including all this code, I guess I have to change something in my code but you don’t mention anything about that. What do I have to pass as arguments to the function myHref??!!

  4. @maher – my_scroll() function expects parameters in form “?param1=a&param2=b&param3=c” to send to the page. scroll parameter will be added at the end and read in set_scroll() function. You also wrote myHref instead of my_scroll so the problem might be in calling non existing function.
    ;)

  5. Sorry for the elementary question, I’m pretty new to javascript. Could you explain what calls the function my_refresh()? I see the function defined in the code, but there is no event that calls it.

  6. @Ben – my_refresh() was modification of original my_scroll() function to maintain vertical scroll position in auto-refresh mode. Inside window.onload you can see setTimeout() method which will call my_refresh() after 2 seconds. The setTimeout() method calls a function after a specified number of milliseconds.

  7. dbunic

    I have tried this with IE8 and can not get it to work. Have you looked at any update for this?

    Thanks.

  8. @Don – This script should work in IE8. I just open this page in IE8 and click on my_scroll() link. After page is loaded, scrollbar has been set to the exact location of previous scrollbar position. Do you have problem with this page or your own example?

  9. Hey dbunic

    I am trying to add your function to a form that redirects to a page and then back to the original.

    When I add your function to the action value of the form, the form does not seam to post any of the fields within it. Do you know what I am doing wrong? (form code below)

  10. @Alasdair – Somehow your code is cut out from the comment. I guess that Askimet had his fingers on it (I will try to fix it later). Anyway, the trick is to send scroll parameter to the server with other needed parameters. Your script (PHP, ASPX …) should accept scroll parameter and send it back to the page in URL. JavaScript code set_scroll() (hooked in onload event listener) will search for scroll parameter in query string. If scroll parameter is found, then new position of the vertical scroll bar will be set.

    The effect should be like click on this refresh link.

  11. Hello to all coders of quality & others.

    I’m a bit confused… how do I get the scroll position to the scroll parameter. Here’s what I’m doing: I’m including this code at the top of my form section:

    <input type="hidden" name="scroll" value="">
    

    How do I get the actual parameters into the value?
    Thanks!

  12. Greg McMahan – First, I renamed function to my_scroll() and it can be called without input parameter. If function is called without parameter then it will return current vertical scroll position. Here is example with button:

    and the HTML source:

    <input type="button" value="Click me" onclick="alert(my_scroll())"/>
    

    So, on the same way you can call this function and set scroll value to your form element before form submission. After page is refreshed, it’s important that scroll parameter is in URL so set_scroll() can read scroll value and set vertical scroll position.

    PS – I have prepared several examples in redips11.tar.gz package so you can download it (download link is below post title) and see how script works.

  13. oh very cool. for simply refreshing a page (with existing parameters) what worked most easily for me was 1) copy all the code from the top of this page (all the functions). 2) replace my_scroll function… with the my_refresh() function (posted 12.04.2010. at 18:10). then call it from a ‘refresh’ button:

    great. thanks.

  14. Hi, nice code. I really needed this, but I have problem to connect function myscroll with my inner function. Here is the problem:

    function ShowDescription($link, $name) {
        global $url;
        echo '';
        //echo '';
        echo $name;
        echo '';
    }
    

    In commented line is the old working code and cannot figure out how to put this piece of code to parameters of function my_scroll. I will be gratefull for help, cause I am not JS programmer and have no idea how to search solution for a little bizzare problem

  15. @Masztalski – my_scroll is a JavaScript function and cannot be called on server side (i.e. in PHP, JSP …). The main purposes of my_scroll function is to read current vertical scroll position in a moment of clicking on a link or submitting a form. Scroll value will be send to the server as a scroll=value pair. Server script should accept scroll position and send it back in URL to the to the browser. After browser finishes with page loading, it will run set_scroll function to read scroll value from the URL and to set vertical scroll position. If scroll parameter doesn’t exist in URL then nothing will happen. Please dowload redips11.tar.gz (download link is below post title) package and see several prepared examples. These examples are a good start point. Cheers!

Leave a Comment