Smooth scrolling back-to-top link

04 October 2011

With jQuery it's very easy to create a smooth scrolling back-to-top button on your website.

Add a button on your page, somewhere near the bottom of your page. My back-to-top button is visible when you scroll down more than 800 pixels and it stays in the viewport due to a stay-in-view-script I wrote. Anyway, add a button:

<a href="#top" class="toTopLink"><span>Jump back to top</span></a>

And style this button. My button is styled like this:

.toTopLink {
  floaT: left;
  margin-left: 138px;
  displaY: block;
  width: 50px;
  height: 50px;
  background: #CCCCCC; 
  position: relative;
  display: none;
  text-decoration: none;
}
.toTopLink:before {
  position: absolute;
  content: '';
  left: 50%;
  margin-left: -15px;
  margin-top: -15px;
  top: 50%;
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-bottom: 30px solid #DDDDDD;
}
.toTopLink:after {
  position: absolute;
  content: 'Back to top';
  top: 100%;
  color: #BBB;
  font-style: italic;
  width: 200px;
  left: -20px;
  top: 60px;
  font-size: 18px;
}
.toTopLink span {
  display: none; 
}


But all the magic happens in a simple and clean jQuery function:

$('.toTopLink').bind('click',function(){
  $('html, body').animate({
    scrollTop:0
  }, $(window).scrollTop() / 3);
  return false;
});

The magic happens in the formula that sets the animation speed.

$(window).scrollTop() / 3

If you'd set the animation speed to a fixed number the animation would take (for example) 500 milliseconds to scroll 800 pixels, but it would also take 500 millisecond to scroll al the way up from a long page with over 10.000 pixels. The second options would scroll superfast.

But with this formula, it takes the current scroll position and devides it with three to ensure a smooth and steady scroll speed, no mather where you are on the page. Awesome!

Play with the subdevision to get faster or slower scrolling speeds. Lower number means higher scrollspeed and a higher number means lower scrolling speeds.

There's one extra part to this script and that's the show-when-scrolled-further-than-x-pixels script. Add a scroll-listener to the page:

$(window).bind('scroll', function(){
        checkScrollPos();
    });
    checkScrollPos();

This function calls the "checkScrollPos" function every time the page is scrolled, and immediately at page load (you might want to add this script to a document.ready function). The checkScrollPos function itself is quite simple:

function checkScrollPos() {
    if ($(window).scrollTop() > 600) {
        $('.toTopLink').fadeIn(1000);
    } else {
        $('.toTopLink').fadeOut(1000);
    }
}

The function also has a fallback, because of the #top anchor in the link. This link isn't executed because of the "return false" in the onclick function, but if that one fails it will still execute the original #top anchor. Just make sure you got an anchorpoint in the top of your page to get it to work.

What goes where?


As stated in the comment section it isn't really clear for novice webdevelopers to know what code goes where. Well, that's also quite easy. Hang on!

Open up your page source code and search for the head section. This is always the first chunck of code after the opening tag. If not, move it there. Look in the head section for some tags that start with script... These are the includes of the remote JS files. If you find these lines, look for a line that includes a file (src="...") that looks like "jquery.js". Or something like "jquery.1.9.1.min.js" or whatever. As long as it has "jquery" in the filename it will most likely be jQuery that's being included. If not, download jquery, put it somewhere on your server or computer, copy one of the script tags and change the link to the location you just uploaded jquery to.

Now we have made sure that jquery is available on the page. Now add a new script tag to the head, as close to the close head-tag as possible. Make it look like this:

<script type="text/javascript">
$(document).ready(function(){
  // code goes here.
});
</script>

Now add all scripts from the tutorial above:

<script type="text/javascript">
$(document).ready(function(){
  $(window).bind('scroll', function(){
          checkScrollPos();
  });
  checkScrollPos();

  $('.toTopLink').bind('click',function(){
      $('html, body').animate({
          scrollTop:0
      }, $(window).scrollTop() / 3);
     return false;
  });
});

function checkScrollPos() {
    if ($(window).scrollTop() > 600) {
        $('.toTopLink').fadeIn(1000);
    } else {
        $('.toTopLink').fadeOut(1000);
    }
}
</script>
You must have JavaScript enabled to use this form!

Leave a comment!

  1. Your mail is safe with me. It's only only used to display your Gravatar image!

6 comments

  1. Gravatar

    Bablu Baghel

    23 May 2014

    I scrool bar is so usefull for some one

    This is not active when on middle of the rest page

    Help If any

    Thanks
    Bablu

  2. Gravatar

    Isso

    25 October 2013

    Hey, this works great! I will be using it on IssoBeats.com, which I will be launching this week. Many thanks for the excellent script!

    Cheers,
    Isso

  3. Gravatar

    Steven Horn

    16 October 2013

    I can't get this to work. I didn't implement any of the CSS and I didn't place a span within the <a></a> and I'm relying on jQuery that's already in my site. But the script is in the head and the link has the right class. I can't figure what's missing. websentia[dot]com

  4. Gravatar

    Johan

    04 April 2013

    Thanks for your kind words, Mark! I really appreciate it :)

    I'll add a section to the tutorial anytime soon to explain what goes where ;)

  5. Gravatar

    Mark

    04 April 2013

    First off, I'm pretty sure you're a genius. The fact that this text box is pulsating cyan blue as I type is already blowing my mind not to mention the font face for "Name", "Email", etc. Very sweet. Even the font in this text field is insane (can't place it but whatever font that uses this style "g" is my kinda font)!!

    Pardon my incredibly noob web design/development ignorance but I have NO idea where to place the code that's so eloquently referenced on this page.

    While you have nifty, easy clipboard buttons (thank you) I have no idea if I'm supposed to paste this into the header of the index.html page, create a separate "jquery.js" page, paste some of the code into the CSS sheet; I'm totally lost. Then again I'm about as wet behind the ears as they come for web designers.

    Because of my limited experience I find it best to purchase a template and reverse engineer it to do my bidding but only cosmetically. I'm not changing formatting or replacing div tag positions. Maybe a pixel count change here or there but I mostly make color and graphic changes (I'm more of a print designer breaking into the web design field).

    Anyway, any advice you can add to this blog entry that states specifically where this code is supposed to go would be greatly appreciated for the incredibly uninitiated.

    The template I'm using already has a "js" folder so there's obviously JQueries and the like being used in the site. Hopefully whatever I add doesn't muck it up. I've already broken the site once and never figured out how I did it even when referencing the original code line-by-line to my changes. Thank God for back-ups.

    Thanks.

  6. Gravatar

    diego.pk7

    09 December 2012

    how about a .scrollBottom() function? ._.