LATEST #JQUERY NEWS

jQuery Snippets: Back to Top Button


One common way to use jQuery is to add a useful and functional “Back to Top” button to your pages and projects. This feature is a prominent and popular one on many websites as the Back to Top trend continues to grow — you may have noticed it when shopping online. The feature is very popular on ecommerce sites. The way it works is actually really simple. All you need is an anchor tag (preferably one placed towards the bottom of the page) and a few quick lines of jQuery.

Here’s what your anchor tag should look like:

<a href="#top">Back to Top</a>

Of course, your anchor tag can say anything you like, or you could even choose to replace the text with an arrow-shaped graphic or an image. Customize the HTML to suit the needs of your individual projects.

Your jQuery code should be as follows:

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

You select the Back to Top anchor tag by using attribute selectors to make sure that your jQuery code will apply to the anchor tag with the #top value for the href attribute. From there, the rest of the code is fairly simple. The body of your page will scroll back to the very top of the page (0 refers to the vertical position of the scrollbar), and the “slow” attribute determines the speed of the scroll. This can also be customized — you can insert fixed values (slow, fast, etc) or numerical values that determine the milliseconds it should take for the page to scroll back to the top position.

The style of your Back to Top button and the speed/position of your scroll are completely customizable and up to you. If you want the button to be hidden and only appear after the user has scrolled a certain amount down the page, you’ll need to add the following lines to the beginning of the code:

$(window).on('scroll', function() {
 if ($(this).scrollTop() > 100) { 
 $("#backToTop#).fadeIn();
 } else {
 $("#backToTop#).fadeOut();
 }
});

In the example above, the anchor tag has the ID #backToTop, and the button will appear after the user scrolls 100 pixels down the page.