Wednesday 9 January 2013

Back to Top using 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 an anchor tag and some text:

<a href="javascript:void(0)" class="backtotop">Back to Top</a> 



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.

No comments:

Post a Comment