<div class="myDiv"></div>
<button class="scrollToTopBtn">TOP</button>
.myDiv {
background: linear-gradient(#e66465, #9198e5);
height: 200vh;
width: 100%;
}
.scrollToTopBtn {
position: fixed;
bottom: 50px;
right: 50px;
display: block;
padding: 8px 4px;
cursor: pointer;
transform: translateY(100px);
opacity: 0;
transition: transform 0.5s, opacity 0.3s;
}
.showScrollBtn {
transform: translateY(0);
opacity: 1;
}
document.addEventListener("scroll", handleScroll);
// get a reference to our predefined button
var scrollToTopBtn = document.querySelector(".scrollToTopBtn");
function handleScroll() {
var scrollableHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var GOLDEN_RATIO = 0.5;
if ((document.documentElement.scrollTop / scrollableHeight ) > GOLDEN_RATIO) {
//show button
if(!scrollToTopBtn.classList.contains("showScrollBtn"))
scrollToTopBtn.classList.add("showScrollBtn")
} else {
//hide button
if(scrollToTopBtn.classList.contains("showScrollBtn"))
scrollToTopBtn.classList.remove("showScrollBtn")
}
}
scrollToTopBtn.addEventListener("click", scrollToTop);
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.