Programmatically Animated Page Scroll with jQuery

With the increasing use of AJAX to populate a page without reloading it, you come to find out that you’d like to get your users back to a certain point in the page, if not the top. If you where to navigate to a new page via the browser, you always end at the top. But when just replacing a container with new information this doesn’t happen. Depending upon your scenario, this may be a good idea for usability.

The following code snippet is a simple example. It will detect if your user is below 210 pixels on the screen. If you are then it will animate the page, scrolling it up to the 210px mark. You may want to use an extended jQuery .position() method to find the top of your #result container instead of using a static page height value.

$.get( 'ajax/test.html', function( data ) {
    $( '#result' ).html( data );

    if ( $( window ).scrollTop() > 210) {
        $( "html, body" ).animate({
            scrollTop: 210
        }, "slow" );
    }
});
Advertisements

#jquery, #scroll