jQuery smooth scrolling

How to perform a nice, smooth scrolling effect to an anchor tag on the same page. You can pass a parameter to this so it’s reusable, and the link has graceful degradation for anyone who’s mad enough to disable JavaScript.

Remember to include jQuery first. Next, the function:

// Scroll to anchor (passed parameter)
function scrollTo(anchor){
	$(‘html,body’).animate({ scrollTop: $(anchor).offset().top }, 1000);

Call the function above by passing an anchor tag as a parameter (e.g the div class/id you want to link to). In this example we’re linking to a div with the id footer :

The href value is the fallback, just incase JavaScript is disabled, onclick runs the function and passes the parameter, return false stops the link from jumping to the top of the page before scrolling.

How easy is that!

If you found this useful please consider a small donation: