Scroll to an element using jQuery

January 03, 2014 | Last tested: June 2015 | 662 views | Comments

Smoothly scroll to an element using the animate() function of jQuery.

For example.

Scroll to the header div from a click of a button from the bottom of the page.

HTML code
<div id="header"><h1>Header</h1></div>
<p>The quick brown fox jumps over the lazy dog.</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p>The quick brown fox jumps over the lazy dog.</p>
<h4>Footer</h4>
<div><a href="" id="scroll">Click here to smoothly scroll back to the Header.</a></div>

jQuery code.

$('#scroll').click(function(e){
	$('html, body').animate({
		scrollTop: $('#header').offset().top
	},400);
	
	e.preventDefault();
});

 

Related Tutorials


Must Read