Problem:
So I already know how to make a back to top button using the scrollintoview
function in javascript. It works fine because I make it scroll into view of an element at the top of my webpage. However, how do I make it only show if user scrolled down the page a bit and make it dissapear when back at top? It would also be nice if it can fade in and out when user scrolls. This is my current code for an example button:
function toTop() {
document.getElementById('top').scrollIntoView();
}
#content {
width:100%;
height:1000px;
background-color:blue;
}
*{
scroll-behavior:smooth;
}
button {
position:fixed;
bottom:20px;
right:20px;
}
<div id="top">hello world</div>
<div id="content">content</div>
<button onclick="toTop()">to Top</button>
Solution:
Here is one solution you can try.
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
const backToTopBtn = document.getElementById("backToTopBtn");
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
backToTopBtn.classList.add("show");
} else {
backToTopBtn.classList.remove("show");
}
}
function scrollToTop() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
#backToTopBtn {
display: none;
position: fixed;
bottom: 20px;
right: 20px;
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
#backToTopBtn.show {
display: block;
opacity: 1;
}
<button id="backToTopBtn" onclick="scrollToTop()">Back to Top</button>