How to tell when you're at the bottom of the page:
if ( document.documentElement.clientHeight +
$(document).scrollTop() >= document.body.offsetHeight ) {
...
}
Here's how to scroll to the top of the page:
$('html, body').animate({scrollTop:0}, 'slow');
Here's how to combine those to and fade a link in to scroll to the top of the page when you hit the bottom of the page (the link only gets reset if you click on it, since that made more sense to me).
This makes use of .animate(). Out of 4 possible arguments, I used 3: properties, duration, and a callback.
$(function() {
$(window).scroll(function() {
var totalHeight, currentScroll, visibleHeight;
// How far we've scrolled
currentScroll = $(document).scrollTop();
// Height of page
totalHeight = document.body.offsetHeight;
// Height visible
visibleHeight = document.documentElement.clientHeight;
// If visible + scrolled is greater or equal to total
// we're at the bottom
if (visibleHeight + currentScroll >= totalHeight) {
// Add to top link if it's not there
if ($("#toTop").length === 0) {
var toTop = $("<a>");
toTop.attr("id", "toTop");
toTop.attr("href", "#");
toTop.css("display", "none");
toTop.html("Scroll to Top of Page");
// Bind scroll to top of page functionality
toTop.click(function() {
// Use animate w properties, duration and a callback
$('html, body').animate({scrollTop:0}, 'slow', function() {
$("#toTop").remove();
});
return false;
});
$("body").append(toTop);
$("#toTop").fadeIn(3000);
}
}
});
});