scullclever
1/21/2013 - 2:48 PM

Simple back-to-top button with jQuery.

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);