jQuery Snippets: Scroll to Top
This simple and straightforward jQuery code snippet can be used to easily create a "scroll to top" effect on any of your pages or projects. If you've not familiar with the scroll to top concept, it basically involves a link or button of some sort that is typically placed in the bottom corner of a page. When the link or button is clicked, the page scrolls smoothly back up to the top, so that the user doesn't have to scroll manually.
Here's the code that you'd need to implement this effect on your pages or projects:
The HTML
Let's start with HTML for a scroll to top link. It should be pretty straightforward, and look something like this:
<a href="#" class="to-top">
Back to Top<
/a>
Back to Top<
/a>
The text can say anything you'd like, and you should feel free to get creative with the styling. Many designers and developers prefer links that resemble buttons, rather than plain text links, for this particular purpose.
The jQuery
Like the HTML, the jQuery for this effect is actually quite simple. Take a look at the snippet below to see for yourself how it works:
$(document).ready(function() {
$('.to-top').click(function() {
$('html, body').animate({scrollTop: 0}, 300);
})
});
As you can see, when the 'to-top' link is clicked, the animation method is applied to the html and the body elements, using the scrollTop value, which scrolls the entire page back up to the top. The numerical value (in this case, 300) defines the speed at which it should take for the page to scroll back up to the top in milliseconds.