jQuery Tutorial: Animate scroll to anchor link

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we are going to use jQuery to animate the scroll to an anchor link.

You can see demo here.  And the full code by doing “view source” in the browser.

Given that we have a page of text such as this with a link “click here” that takes the user to the anchor link “come here” …

jump anchor link

jump anchor link

We add jQuery library from the Google CDN (content delivery network) and jQuery ready script.   And within jQuery document ready event, we tell jQuery to find the “a” link element with href=”#comehere” (this is the link that is being clicked).

animate scroll to link

animate scroll to link

 

When this link is clicked, we find the top offset of the target anchor link which is (‘a[name=comehere”]’).   If you add an …

alert(targetOffset)

you will see that the top offset is the number of pixels to the target anchor link from the top of the page.

The next statement tells the browser to scroll the body to that position of targetOffset.  Do it with animation at a speed of 1000 microseconds (in other words, one second).   You can adjust the speed of the animation by changing 1000 to something smaller or larger.   Larger time means slower speed.

The “e.preventDefault()” is to tell browser to not perform its normal click behavior (because we are running our jQuery code instead).

 

Also take a look at the jQuery Animate Scroll to Anchor Link video tutorial created by Webucator which offers more jQuery training.