How to Make a Jquery Back to Top Link
It’s the small things in a website that makes your clients go OOOHhhhh… Things like animating the scroll when someone clicks a back to top link can give you some serious brownie points. Considering it’s online a couple of extra lines of code it’s well worth it.
What We are Building
Simply put, we’re going to create a looooong HTML page that has back to top links through out. When you click on one of these links it will scroll to the top in an awesome animated fashion.
Step 1: The Content
This should be pretty straight forward, you’re site should already have content, but in the case of an example we have to get some, and there has to be enough to scroll. I just took mine from the w3 standards website…as it should be already HTML compliant
Now throughout you just need to add some back to top links with anchor tags to some element at the top of the page. In our case we have a div with an id of top. So our anchor tag should look something like…
Step 2: The jQuery
At the bottom of your html just add the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!-- Include jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> //Click event handler for any anchor that has an href that ends in top $('a[href]$="top"').click(function() { //Animates scroll to the top of the page...and take 1 second to do it. $('html, body').animate({ scrollTop:0 }, '1000'); //return false to prevent the default action of the anchor tag when clicked. return false; }); </script> |
Nothing too special here. Just a click event for the back to top links that animates the scroll.
That’s all there is to it. Enjoy making your site that much cooler.

