Fred
Fred

Reputation: 45

How to scroll to a part of the page using jQuery?

My code scrolls the user to the bottom of the page:

var $elem = $('body');
$('html, body').animate({scrollTop: $elem.height()}, 800);

How can it be modified to take the user to the part of the page where there is a h3 tag with the id "myTitle":

<h3 id="myTitle">Hello</h3>

Upvotes: 4

Views: 384

Answers (4)

Prasanna
Prasanna

Reputation: 11544

$('html, body').scrollTop($("#myTitle").offset().top)

Upvotes: 0

John Magnolia
John Magnolia

Reputation: 16793

This is a brilliant example

That even works with JS turned off. Additionally this adds the #myTitle to the URL allowing bookmarking.

Upvotes: 0

James Allardice
James Allardice

Reputation: 165941

You can get the offset of the element from the top:

var position = $("#myTitle").offset().top;

You can then use that as the value to scroll to.

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

How about:

var $elem = $("#myTitle");
$('html, body').animate({scrollTop: $elem.offset().top}, 800);

using .offset().

Here's a working example: http://jsfiddle.net/naTjL/

Upvotes: 4

Related Questions