Simple Scroll to top using JQuery
Link that takes you to the top of the page when you have scrolled down the page
With most of the sites having infinite scroll these days it is important to have a little link somewhere at the bottom of the page which takes the user back to the top of the page. This is a an important piece of functionality especially if the page becomes really long.
We are going to achieve the following -
1) The scroll to top link is hidden when the page loads.
2) When the user starts scrolling, the link fades in and is clickable
3) User can click on the back to top link to scroll back to top and the link fades out.
Lets start with the simple HTML. It is a simple anchor tag with a class “backtop”. This will act as a link to bring the user back to top.
<a class=”backtop”></a>
CSS
.backtop{/* this could be any up arrow image. You can download the one I am using from the demo page*/ background:url(up_arrow.png); text-decoration:none; position:fixed; /* to align the anchor tag at the bottom right of the page*/ bottom:20px; right:20px; width:128px; height:128px; cursor:pointer; opacity:0.5; display:none; /* display none when the page loads first */}/* to get hover effect */.backtop:hover{ opacity:1;}
jQuery
Now lets do the important jQuery part. It uses a simple, easy to understand 15 line jQuery code to achieve the whole thing.
/* run this when the window starts scrolling */$(window).scroll(function(){ /* if the user scrolls more than 100 height, show the backtop link else hide it */ if ($(this).scrollTop() > 100) { $(‘.backtop’).fadeIn(); } else { $(‘.backtop’).fadeOut(); }});$(document).ready(function() {/* run this function when backtop is clicked */ $(‘.backtop’).click(function() {/*bring the scroll back to top of the page */ $(‘html, body’).animate({scrollTop:0}, ‘slow’); return false; });});