/* The start of back to top button */
var timeout = null,
divider = 2,
minimumScrollbarPosition = 900;
$(window).scroll(function() {
if (!timeout) {
timeout = setTimeout(function() {
clearTimeout(timeout);
timeout = null;
checkPosition();
}, 200);
}
});
function checkPosition() {
if ($(this).scrollTop() >= minimumScrollbarPosition) { // Checks if the value of scrollTop is greater than 200
$('#back-to-top').fadeIn(500); // Fades in if true
} else {
$('#back-to-top').fadeOut(300); // Otherwise fades out
}
}
// Animate the scroll to top
$('#back-to-top').click(function(event) {
event.preventDefault();
var scrollSpeed = $(window).scrollTop() / divider;
$('html, body').animate({
scrollTop: 0
}, scrollSpeed); // sets scrollTop value to 0(top of page) scrollSpeed references speed
})
<div id="home"></div>
<div id="back-to-top">
<a href="#home"><i class="fa fa-3x fa-arrow-up" aria-hidden="true"></i></a>
</div>
body {
height: 2000px;
}
#back-to-top {
display: none;
position: fixed;
right: 20px;
bottom: 20px;
}
External resources loaded into this fiddle: