CSS-Plus
CSS-Plus
Play with web technologies

Create a scrolling anchor link with jQuery

November 30, 2010
Attention: This article is old and the content is outdated. I've left the article here for historical purposes.

I've been meaning to do this tutorial for a while now and it seems as if I'm finally getting around to it!

Very simply put, this will function like a normal internal anchor link or named anchor link, but will scroll to the specified destination instead of merely jumping there. It's a really easy-to-implement and awesome thing to add to almost any website.

I'm going to jump right into it.

The HTML

All that is needed for this example is an element to click, and an element to scroll to.
<a id="scroll">Click here to scroll</a>
<img src="images/cat.png" alt="cat" />
I've decided to scroll to an image of a random cat, however I think this would be most useful for something like a table of contents.

The jQuery/Javascript

We will be using the click() event, animate effect, scrollTop() manipulation and offset manipulation.
// When the Document Object Model is ready
jQuery(document).ready(function(){
	// 'catTopPosition' is the amount of pixels #cat
	// is from the top of the document
	var catTopPosition = jQuery('#cat').offset().top;
// When #scroll is clicked
jQuery('#scroll').click(function(){
	// Scroll down to 'catTopPosition'
	jQuery('html, body').animate({scrollTop:catTopPosition}, 'slow');
	// Stop the link from acting like a normal anchor link
	return false;
});

});

Fairly simple and straight forward jQuery. Note: jQuery('html, body') is necessary for cross-browser compatibility.

Demo