jQuery Scroll To Top

Tutorial on jQuery Scroll to Top at https://www.aritsltd.com/blog/frontend-development/jquery-scroll-to-top-function-snippet/

by Fahim Hossain

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<section class="topSection">
        Top Section
</section>
<section class="bottomSection">
        Bottom Section
</section>
<!-- You will need to copy the following code for your implementation -->
<a href="#" id="scrollTop">^</a>

CSS

.topSection, .bottomSection{
  background: white;
  height: 500px;
  display:flex;
  align-items: center;
  justify-content: center;
}

/* You need only the following css class for your project */
#scrollTop{
    opacity:1;
    width:30px;
    height:30px;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-items: center;
    text-align: center;
    background-color: grey;
    position:fixed;
    bottom:5vh;
    right:5vh;
    transition:all 0.15s ease-out;
}

JavaScript

var scrollAmountBeforeDisplay = 30;
var scrollTransitiontime = 1200;
var opacityTransitionTime = 150;


$(document).ready(function(e) {
    scrollTopFunction();
})


//1. Scroll to Top of the Page
function scrollTopFunction() {
    console.log($(window).scrollTop());
    if ($(window).scrollTop() < scrollAmountBeforeDisplay) {
        $('#scrollTop').fadeOut();
    }
    $(window).scroll(function() {
        //If scroll amount is sufficient to display
        if ($(this).scrollTop() > scrollAmountBeforeDisplay) {
            if ($('#scrollTop').css("opacity") == "0") {
                $('#scrollTop').css("display", "block");
                setTimeout(function() {
                    $('#scrollTop').css("opacity", "1");
                }, opacityTransitionTime);
            }
        }
        //If scroll amount is insufficient to display
        else {
            if ($('#scrollTop').css("opacity") !== "0") {
                $('#scrollTop').css("opacity", "0");
                setTimeout(function() {
                    $('#scrollTop').css("display", "none");
                }, opacityTransitionTime);
            }
        }
    });
    $('#scrollTop').bind("click", function(e) {
        e.preventDefault();
        window.location.hash = '';
        $('html, body').animate({
            scrollTop: 0
        }, scrollTransitiontime);
    });
}