Skip to content

Instantly share code, notes, and snippets.

@jeremyboggs
Created January 21, 2013 14:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jeremyboggs/4586585 to your computer and use it in GitHub Desktop.
Save jeremyboggs/4586585 to your computer and use it in GitHub Desktop.
Simple back-to-top button with jQuery.
/**
* Show or hide the button depending on the scroll position.
*/
function animateButton() {
var button = $('#back-to-top');
var scrollPosition = $(window).scrollTop();
if (scrollPosition > 400) {
button.fadeIn();
} else {
button.fadeOut();
}
}
/**
* Create the button and append it to the body.
*/
$(function () {
$('<a id="back-to-top">Back to Top</a>')
.click(function () {
$('html,body').animate({
scrollTop: 0
}, 1200);
return false;
})
.appendTo($('body'));
});
/**
* Run the animateButton function on window resize, scroll, and load.
*/
$(window).resize(animateButton);
$(window).scroll(animateButton);
$(window).load(animateButton);
@patrick-wc
Copy link

Great, cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment