Monday, June 10, 2013

Create a scrolling anchor link with jQuery

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.

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
// '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('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.

No comments:

Post a Comment