Automatic scroll the page to a div after 5 seconds

giovanni picture giovanni · Mar 18, 2013 · Viewed 15.9k times · Source

I'm new in javascript, now I'm trying to do that, as the title, I've a page which has a div at the top that is as big as the page with a video in it, followed by several sections like this:

<div id="first" style="height:100%; width:100%"></div>
<section id="second" style="height:100%; width:100%"></section>
<section id="third" style="height:100%; width:100%"></section>

Now I need 5 seconds after the page is loaded to scroll automatically the page to #second. I've tried many ways but have failed and haven't found nothing that works properly.

Thanks

Answer

zzzzBov picture zzzzBov · Mar 18, 2013

I'm feeling generous, so I'll just give you the code this time.

$(window).load(function () {
    //normally you'd wait for document.ready, but you'd likely to want to wait
    //for images to load in case they reflow the page
    $('body').delay(5000) //wait 5 seconds
        .animate({
            //animate jQuery's custom "scrollTop" style
            //grab the value as the offset of #second from the top of the page
            'scrollTop': $('#second').offset().top
        }, 300); //animate over 300ms, change this to however long you want it to animate for
});