Ajax save scroll position of div before hashchange (BBQ Plugin)

1.4k Views Asked by At

I'm using the jquery BBQ plugin for my ajax hashchange events and history states. My issue is that it doesn't save the scroll position, so when I use the back button the scrollbar isn't positioned where it was before the hashchange, but rather the same pixel position it was before the back button was pressed. I've seen that this is a problem for many, and some mention using cookies but I have no idea how to do so with the BBQ plugin, so all help is appreciated. Ideally I would like it so that when a page is navigated to normally, the scroll is at the top, but when the back button is pressed the scroll is positioned where it was on that page. This is my code:

$(function(){

var cache = {
    '': $('.content')
};

$(window).bind( 'hashchange', function(e) {
    var url = $.param.fragment();
    var scroll = $('#wrapper').scrollTop();
    $( '.contentarea' ).children( ':visible' ).hide();
    if ( cache[ url ] ) {
        cache[ url ].show();
    } else {
        $( '.content-loading' ).show();
        cache[ url ] = $( '<div class="pageURL"/>' )
        .appendTo( '.contentarea' )
        .load( url, function(){
            $( '.content-loading' ).hide();
        });
    }
})

$(window).trigger( 'hashchange' );

$('#btn-back').click(function(){
    parent.history.back();
    return false;
});
});

Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

Found an easier way to solve the problem with the desired results.

Rather than loading the content straight into the container div with, within the template file of the page being loaded, wrap the entire page content within it's own container div. Make it's width and height 100% so that it is the exact size as the container div the content is being loaded into, and enable overflow on the new container div (best to set overflow to hidden on the original container div).

Doing this, the original container div will never have a scroll position, but the new container within the template file will, and that is the div and scroll position that will automatically be kept in the browser history along with the page. Now, going forward and then back will keep the position of the new container and the user will be exactly where they were before the left the page.

;-)