Animate scroll to ID on page load

Adi picture Adi · Jul 13, 2011 · Viewed 315.6k times · Source

Im tring to animate the scroll to a particular ID on page load. I have done lots of research and came across this:

$("html, body").animate({ scrollTop: $('#title1').height() }, 1000);

but this seems to start from the ID and animate to the top of the page?

The HTML (which is half way down the page) is simply:

<h2 id="title1">Title here</h2>

Answer

BumbleB2na picture BumbleB2na · Jul 13, 2011

You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);