<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);
});
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.