A couple of projects I’ve worked on recently have led to some huge pages, spanning down thousands of pixels, and so it seemed appropriate (from a usability perspective) to provide a way to get back to the top of the page without the need to sit scrolling the mouse wheel for ages on each page.
Of course I could have taken the easy route many developers take of scattering <a href="#top">Back to top</a>
tags all over the page and adding something like id="top"
to the <body>
tag, but it’s not the most elegant solution – plus I’ve seen some examples of it looking pretty ugly when it’s overused.
For that reason, I decided to write what I think is a far more elegant, jQuery JavaScript based animated back to top scroller which I’ve implemented on several sites – you can see an example of this on this site (just scroll down a bit and you’ll see it in the bottom right!)
So, for anyone interested, here’s how I did it.
(tl;dr – Don’t care about the explanation? Here’s the CSS you need, and here’s the jQuery.)
The CSS bit
Firstly, here’s a bit of CSS to get you started:
.back-to-top { background-color:#333; border:1px solid #222; border-bottom:0; bottom:0; color:#bbb; display:none; float:left; font-size:11px; padding:10px 10px 5px; position:fixed; right:30px; text-decoration:none; z-index:99999; -webkit-border-radius:10px 10px 0 0; -moz-border-radius:10px 10px 0 0; border-radius:10px 10px 0 0; }
Nothing too special here. It simply applies some colour, a bit of padding, the affixes it to the bottom of the screen and hides it out of view until it’s needed.
You’ll notice I’ve also used a float:left;
, which looks a bit out of place. The reason is that although I’d prefer to use a display:inline-block;
, for simplicity you’ll see later on that I’m using the jQuery slideUp()
and slideDown()
functions, which both end up with a block element – unless you know the width of the element (which, assuming you guys will want to change the text to something else, I don’t!).
So, either whack this in your stylesheet (or in the <head>
between some <style type="text/css"></style>
tags and you’re ready to add the JavaScript.
The jQuery bit
Remember you’ll need to have the jQuery libraries loaded to use this. So, assuming you’ve already dealt with that bit, here’s the JavaScript:
$(document).ready(function() { $('body').append('<a href="#top" class="back-to-top">Back to top</a>'); $('a.back-to-top').click(function(e){ $('html, body').animate({scrollTop:0}, 'slow'); e.preventDefault(); }); $(window).scroll(function() { if ($('body').offset().top < $(window).scrollTop()) { $('.back-to-top').slideDown('fast'); } else { $('.back-to-top').slideUp('fast'); } }); });
First thing you’ll notice is that this method doesn’t require you adding any HTML to the page yourself – the $('body').append('<a href="#top" class="back-to-top">Back to top</a>');
will do the job of appending the link to to the bottom of the page. This is also where you can change the text displayed on the button – as I used a float earlier, the button will expand as necessary, so feel free to change it to whatever you want.
Next we a have the bit that controls the actual animation. The jQuery click event will capture clicks on the link we added earlier, and run an animated scroll back to the top of the page. Much prettier the instant jump from simply using an anchor tag!
The last part isn’t mandatory, but I think it adds to the effect quite nicely. What’s the point in having the button visible when you’re already at the top??
Note: The $('body')
bit in the last part ensures that the link becomes visible when the top of the body goes out of view – ie, as soon as you start scrolling. If you would rather it appeared, say, when the header went out of view, you could easily change that to reference the top of your content <div>
– so if your content is wrapped in a div with a class of “content”, simply change it to $('.content')
.
So, either whack this in your .js file (or in the <head>
between some <script type="text/javascript"></script>
tags and you’re good to go.
Want it to work in non-javascript enabled browsers?
Seeing as the entire thing is jQuery/javascript powered, the code above won’t work in a non-javascript enabled browser – the button won’t even render, seeing as we’re inserting it into the page using jQuery’s .append
function. To get it working, you’ll need to make a couple of tweaks…
First, either add an id
to your <body>
tag – something like id="top"
(or if there’s already an ID set, just make a note of what it is…)
Next, manually add the following code to your HTML. I’d advise sticking it right at the bottom, just before the closing </body>
tag. Make sure you change the #top
reference to whatever ID you noted down in the previous step.
<a href="#top" class="back-to-top">Back to top</a>
This will build an identical button to the one the JavaScript was inserting automatically.
Finally, remove the following line:
$('body').append('<a href="#top" class="back-to-top">Back to top</a>');
And replace it with:
$('.back-to-top').css('display', 'none');
This ensures that the button you just added is hidden for those that *are* using JavaScript.
Of course, if the user doesn’t have JavaScript enabled, they won’t see animations, autohide, etc, and it’s a little bit more work to implement – but at least it’ll ensure it’s visible for all users, not just the large majority.
So there we have it!
A relatively simple, yet rather nice looking “back to top” animated scroller using jQuery and a bit of CSS. Feel free to use and abuse the code as you see fit, and don’t be afraid to change the styling to fit your own site design!
Oh, and if you’re using WordPress, in the javascript you’ll need to change the $
to jQuery
(as jQuery on WP runs in compatibility mode to allow it to run alongside other JavaScript frameworks, such as prototype).
Enjoy!
Will use when I next update my blog. Thanks. Looking forward to next years post.
Ha! Yeah, I’ve made a late new year’s resolution to post a bit more often. Managed 2 in 2011 – already half way to equalling my record this year 😉
Best tutorial on animated back to top buttons using jquery. After about 6 other tutorials, we chose this method; it’s now on our site (Claja.com)!
Sweet! Glad you found it useful. 🙂
Thanks for this. Just what I was looking for 🙂
Many thanks for this great lesson! Best regards from Friesland, Netherlands. Keimp
Big thanks for share …
Great solution, and it worked first time!
Curiously, a few long pages, but not all, gave trouble on Firefox 28 – the button text did not conform to my CSS color:white style, but reverted to the body a:link color. This was fixed by specifying ‘a style=”color:white” …’ in the js append line, but I never did figure out why only a few pages were affected.
Many thanks for this.
Great and helpful tutorial. I am using this , This is also simple
$(document).ready(function(e) {
var a = 400,
t = 1200,
l = 700,
s = e(“.scrool-top”);
e(window).scroll(function() {
e(this).scrollTop() > a ? s.addClass(“scrool-is-visible”) : s.removeClass(“scrool-is-visible scrool-fade-out”), e(this).scrollTop() > t && s.addClass(“scrool-fade-out”)
}), s.on(“click”, function(a) {
a.preventDefault(), e(“body,html”).animate({
scrollTop: 0
}, l)
})
})