How to scroll a page using jQuery?

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

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

How can it be changed to force the user to go to the part of the page where there is an h3 tag with the identifier "myTitle":

 <h3 id="myTitle">Hello</h3> 
+4
source share
4 answers

What about:

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

using .offset() .

Here is a working example: http://jsfiddle.net/naTjL/

+4
source

You can get the offset of the element from above:

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

You can then use this as a value to scroll.

0
source

This is a brilliant example.

It even works with JS turned off. In addition, this adds #myTitle to the #myTitle URL.

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

All Articles