Search code examples
jqueryautoscroll

Autoscroll to div in jquery .load site


I am loading a website in a div like this:

<script type="text/javascript">
    $(document).ready(function(){
            jQuery('#pagecontainer').load('http://www.example.com' );
    })
</script>       

<div id="pagecontainer" /></div>

The loaded site contains a DIV with id="test". So far so good.

But would it be possible to autoscroll the page to that DIV?

The code below is not working, i think because it cant locate the DIV in the loaded site.

$(function(){
    $('html, body').animate({
        scrollTop: $('#test').offset().top
    }, 2000);
    return false;
});

Thx!


Solution

  • From jQuery doc:

    .load( url [, data ] [, complete ] ):

    where: complete

    Type: Function( String responseText, String textStatus, jqXHR jqXHR )

    A callback function that is executed when the request completes.

    That means you can change the code into:

    $(document).ready(function(){
        jQuery('#pagecontainer').load('http://www.example.com', function() {
            $('html, body').animate({
                scrollTop: $('#test').offset().top
            }, 2000);
        });
    })