Reload page without scrolling up

I am submitting some data with jQuery via ajax, and on success I am refreshing page with

document.location.reload(true);

Is there any way to prevent page scrolling back top the top. I did a bit of research and it seems possible to fool Chrome. I also came across the following function, but not really sure where to place it in order for it to work.

if (window.location.hash) { 
    //bind to scroll function
    $(document).scroll( function() {
        var hash = window.location.hash
        var hashName = hash.substring(1, hash.length);
        var element;

        //if element has this id then scroll to it
        if ($(hash).length != 0) {
            element = $(hash);
        }
        //catch cases of links that use anchor name
        else if ($('a[name="' + hashName + '"]').length != 0)
        {
            //just use the first one in case there are multiples
            element = $('a[name="' + hashName + '"]:first');
        }

        //if we have a target then go to it
        if (element != undefined) {
            window.scrollTo(0, element.position().top);
        }
        //unbind the scroll event
        $(document).unbind("scroll");
    });
}

Since I'm refreshing this page, after submitting via a click on an element, shall i attach it somehow to .click event?

Answers 1

  • We can use cookie to do it.

    Before you reload the page, add cookie for last position of scrollTop:

    $.cookie('last-scroll-top', $(window).scrollTop());
    document.location.reload(true);
    

    And when the page reload, we read the cookie, scroll and delete cookie:

    var lastScrollTop = $.cookie('last-scroll-top');
    if (lastScrollTop) {
        $(window).scrollTop(lastScrollTop);
        $.removeCookie('last-scroll-top');
    }
    

Related Articles