In this tutorial, we will show you how to create an animated scroll to top scroller for long height page content. The method in this tutorial is very simple and basic. Once you have learned it, you can customize the scroller or even add more functions or styles to it.
In the header of your page, create style for the scroller.
<style>
#scroll{
position: fixed;
/**position the scroller**/
bottom: 30px;
/**arrow image**/
background: transparent url(arrow.png) no-repeat left top;
width: 32px;
height: 32px;
cursor: pointer;
/**hide it first**/
display:none;
}
</style>
As you can see, firstly we use fixed position to place the scroller, you can change the bottom value to move the scroller around. And then we place arrow.png (which we have downloaded in step 1) to the background of scroller. Lastly, we hide the scroller, since we don't want it show when page is initially loaded.
We will do the JavaScript in the header section of the page as well
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//fade in/out based on scrollTop value
$(window).scroll(function () {
if ($(this).scrollTop() > 0) {
$('#scroller').fadeIn();
} else {
$('#scroller').fadeOut();
}
});
// scroll body to 0px on click
$('#scroller').click(function () {
$('body,html').animate({
scrollTop: 0
}, 400);
return false;
});
});
</script>
I will explain a bit more of the function above. We start calling javascript function when page is fully loaded:
$(document).ready(function(){
});
First part of the function, we event handler to windows scroll event. When window is scrolled (value of scrollTop is greater than 0), we will fade in the scroller, and when no scroll happens, we fade out the scroller. Second part of the function, we bind event handler to click event of the scroller, when it is clicked, we animate body and html of the document to the top.
And now you have a nice animated scroll to top scroller.
Hopefully you have got the idea of makeing a scroll to top scroller. Next what you need to do is to add your own customization. For example, mouse hover styles to the scroller.
You can download the working copy here.
If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.