Programmatically Animated Page Scroll with jQuery

Posted: October 17, 2012 in JavaScript
Tags: ,

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" );

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s