HTML

<header id="top"></header>
<div class="main">
    <main>
        <a href="#top" class="topbutton preventD">TOP</a>
    </main>
</div>
<footer></footer>

<!--javascript-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

CSS

body{height: 100%;}
header{width: 100%; height: 100px;}
.main{width: 100%; height: 2000px; border: 1px solid gray;
  border-right: none; border-left: none;}
.main .topbutton{position: fixed; bottom: 30px; right: 30px; display: none;}
footer{width: 100%; height: 200px;}

JAVASCRIPT

$(document).ready(function(){
    function preventD(a){
        a.click(function(event){
            event.preventDefault();
        });
    }
    function aniLink(link){
        var target = $(link.attr('href')).offset().top;
        $('html,body').stop().animate({scrollTop:target},800,'swing');
    }

    preventD($('.preventD'));

    $('.topbutton').click(function(event){
        aniLink($(this));
    });

    $(window).scroll(function(){
        var scrollBottom = $(window).scrollTop() + $(window).height();
        var gap = $('footer').offset().top - scrollBottom;
        if($(this).scrollTop() > $('header').offset().top+200){
            $('.topbutton').fadeIn();
        }else{
            $('.topbutton').fadeOut();
        }
        if(scrollBottom < $('footer').offset().top){
            $('.topbutton').css('bottom', 30);
        }else{
            $('.topbutton').css('bottom', 30 - gap);
        }
    });
});