Create a back to top link with jQuery

06.23.2013 by Ilia Raiskin
HTML JQuery UX

Demo Download

A web-page can often be longer than the browser window, which means that you have to scroll down in order to see all contents. But what if a user want to get back to the top of the page after seeing all the contents. You could let him or her scroll up by him or herself. Or you can create a simple "Back to top" link which does the top-scrolling for the user. In this tutorial we'll show you an easy jQuery script which transforms any link you choose into a "Back to top"-link.

HTML

First of all we need an HTML link.

Note that this link brings you to the top of a page without any additional jQuery. We need jQuery to create a nice-looking animation. jQuery also doesn't add any extra strings to the URL - the HTML link without jQuery would add #top to the URL.

jQuery


$(document).ready(function(){
  $('a[href="#top"]').click(function(){
     $('html,body').animate({ scrollTop: $("body").offset().top},
     {duration: 'normal', easing: 'swing'});
     return false;
  });	
});


In the jQuery code we select our HTML-link and animate it. Inside animate() we use scrollTop and then $("body").offset().top as the position that our function scrolls to. You can replace $("body") with any element you want. We set the duration to "normal". You can also use the keywords fast and slow or set the time in milliseconds. If you don't use any additional jQuery plugins you can set swing or linear for easing. In the end of the code we use return false, which prevents our link from going to its target: #top.


About the author

Ilia Raiskin

Ilia Raiskin is a web designer, web developer, blogger and founder of Toolinfy.com.






Comment