Back to top button like Facebook app
by johna | September 15, 2017 | Jquery/Javascript Web Development
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.
HTML
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.
CSS
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
}
JavaScript
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) {
$("#scroll-top").show();
} else {
if ($(this).scrollTop() <= 100 || thisPos > lastPos) {
$("#scroll-top").hide();
}
}
lastPos = thisPos;
}, 150);
$("#scroll-top").click(function() {
$("html, body").animate({
scrollTop: 0
}, 500);
return false;
});
});
Example
Want to see it in action?Example on JSFiddle
Related Posts
Converting dBase IV programs to run in the browser
by johna | September 13, 2024
Some pointless entertainment trying to get some old dBase programs running in the browser.
How to set up a debugging using the Turnkey Linux LAMP stack and VS Code
by johna | December 19, 2023
The second part in my guide to setting up a website and database using the Turnkey Linux LAMP stack.
How to set up a website and database using the Turnkey Linux LAMP stack
by johna | November 18, 2023
If you need to host your own website for the purposes of web development, Turnkey Linux LAMP Stack is an easy to install all-in-one solution that you can set up on a spare computer or a VM (Virtual Machine).
Comments
There are no comments yet. Be the first to leave a comment!