I send you an example and I'll explain it to you.
First we insert the link of the button.
<a href="#" class="scrollup">Scroll</a>
◾Now we add the style to the button.
.scrollup{
width:40px;
height:40px;
opacity:0.3;
position:fixed;
bottom:50px;
right:100px;
display:none;
text-indent:-9999px;
background: url('icon_top.png') no-repeat;
}
We have defined the position of the button as fixed with 100px on the right and 50px on the bottom of the page. We have used the "text-ident" property to hide the text and show the button icon. The "display: none;" property makes the button invisible at the beginning.
The icon for the 'icon_top.png' button is as follows:
icon_top
Now we want the button to be visible if we navigate down. We can do this with the jQuery scroll event.
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
The scrollTop property obtains the current vertical position of the scroll bar (scroll bar). If it is higher than 100px, it shows the button to go up, if it is less than 100px it hides it.
◾The next step is to make the animation to go up the web page by pressing the button.
$('.scrollup').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
The scrollTop property: 0 moves to the beginning of the web page, in the 0px position, and 600 represents the duration of the animation in milliseconds. A higher value means slower animation. You can also use the predefined properties like 'fast', 'slow' or 'normal' instead of using the milliseconds.
◾This is the complete jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
$('.scrollup').click(function(){
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});
});
</script>