jquery - back to top

See JS Fiddle

       $(window).on("scroll",function() {
        if ($(this).scrollTop() > 50 ) {
            $('#toTop').fadeIn(400);
        } else {
            $('#toTop').fadeOut(400);
        }
    });

    $("#toTop").on("click",function() {
        $("html, body").animate({scrollTop: 0}, 1200);
     });

$("#toTop").click(function () {
   //1 second of animation time
   //html works for FFX but not Chrome
   //body works for Chrome but not FFX
   //This strange selector seems to work universally
   $("html, body").animate({scrollTop: 0}, 1000);
});

http://jsfiddle.net/fjXSq/161/


Updated JSFiddle with solution

$(window).scroll(function() {
    if ($(this).scrollTop()) {
        $('#toTop').fadeIn();
    } else {
        $('#toTop').fadeOut();
    }
});

$("#toTop").click(function() {
    $("html, body").animate({scrollTop: 0}, 1000);
 });

First lets create the button.

<a href="#" class="scrollToTop">Scroll To Top</a>

Now we can style the button with the following CSS.

<style>
.scrollToTop{
    width:100px; 
    height:130px;
    padding:10px; 
    text-align:center; 
    background: whiteSmoke;
    font-weight: bold;
    color: #444;
    text-decoration: none;
    position:fixed;
    bottom:75px;
    right:40px;
    display:none;
    background: url('arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
    text-decoration:none;
}
</style>

Copy and paste the following in the Javascript file to add the Javascript functionality.

<script>
$(document).ready(function(){
    
    //Check to see if the window is top if not then display button
    $(window).scroll(function(){
        if ($(this).scrollTop() > 100) {
            $('.scrollToTop').fadeIn();
        } else {
            $('.scrollToTop').fadeOut();
        }
    });
    
    //Click event to scroll to top
    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });
    
});
</script>

Tags:

Jquery