Back to top button like Facebook app

By · September 15, 2017 · 0 comments

The Facebook app on Windows phone has a nice and unobtrusive back to top button that only appears once you scroll past a certain point, and only when you start scrolling up the page.

The following code offers similar functionality using jQuery.


First you need to add the back to top button itself. In this example it's just the text "TOP", but you can replace this with an image or icon font symbol or whatever you want.

This element should be placed just before the closing "body" tag, and not inside any element with "position: relative", unless you want to change how it is positioned.

<a id="scroll-top" href="#" style="display:none;">TOP</a>

Note the href attribute is set to "#". The script below uses jQuery to animate scrolling to the top of the page, but you may wish to use an anchor reference instead here.


To give the button fixed positioning and place it near the top right corner, you will need some styling. You can change the position if you like.

I've also set the font size to 34 pixels in this example.

#scroll-top {
position: fixed;
top: 10px;
right: 10px;
font-size: 34px


Here's the JavaScript (using jQuery) that shows and hides the button as needed.

I use setInterval so I can track when the user is scrolling up.

Where you see the number "100", this is the number of pixels down from, the top that the button will be displayed after. That way it won't be shown over your header and if the user is near the top of the page they don't really need a back to top button then anyway.

$(function() {
var lastPos = $(this).scrollTop();

setInterval(function() {
var thisPos = $(this).scrollTop();
if ($(this).scrollTop() > 100 && thisPos < lastPos) {
} else {
if ($(this).scrollTop() <= 100 || thisPos > lastPos) {
lastPos = thisPos;
}, 150);

$("#scroll-top").click(function() {
$("html, body").animate({
scrollTop: 0
}, 500);
return false;


Want to see it in action?

Example on JSFiddle.

Get the latest posts delivered to your inbox.


There are no comments yet. Be the first to leave a comment!

Leave a Comment

All comments are moderated and rel="nofollow" is in use. Avatars are sourced from – a globally recognised avatar.

Type the numbers from the picture above

About me
John Avis ...mostly about web development and programming, with a little bit of anything else related to the Internet, computers and technology.

profile for John at Stack Overflow, Q&A for professional and enthusiast programmers

Get the latest posts delivered to your inbox. *