Jun
28
2010

Creating a Scrolling Back to Top Button with jQuery


If you take a look way, way, way down at the bottom of this page, you will see a Back to Top button that scrolls the whole page until it reaches to top. It is a pretty simple effect to add to your site and looks a hundred-times cooler than just using your typical anchor name and link. Getting it all to work takes nothing more than a few lines of jQuery version 1.4.2.

First, we need to create our button/link. I am just going to use a span tag and some text:

<span class="backtotop">Back to Top</span>

Next we need to add some jQuery between the <head> tags:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
jQuery('.backtotop').click(function(){
	jQuery('html, body').animate({scrollTop:0}, 'slow');
});
</script>

Remember, you can change the speed by replacing slow with a numerical value. You can also add some easing effects by including the jQuery UI. Read more about easing effects here.

If you liked this, please share it.

Tags: , , , , , , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/95NZDB

Discussion 4 Comments

  1. OptimisticDeveloper on June 29, 2010 at 4:15 am

    It certainly doesn’t in Chrome…

    • c.bavota on June 29, 2010 at 3:00 pm

      Yup. I forgot to add the body tag to the jQuery call. I changed it above. Try it now.

  2. Peter on July 2, 2010 at 10:01 am

    Definitely doesn’t work. You can’t click a span.

    • c.bavota on July 2, 2010 at 10:37 am

      Then you can make it a div or an anchor link with the same class name.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.