Sticky Back-to-Top Button with Smooth Fade
Create a sticky back-to-top button that appears smoothly when scrolling down and fades away when scrolling up, using HTML, CSS, and JavaScript.
Scroll down to see the back-to-top button appear!
Why this works
By toggling CSS classes based on scroll position, the button fades in and out smoothly, providing a non-intrusive yet accessible way for users to quickly return to the top of the page.
Source Code
<button id="backToTopBtn" onclick="scrollToTop()" style="position: fixed; bottom: 2rem; right: 2rem; display: none; background-color: #0d6efd; color: #fff; border: none; padding: 0.75rem 1.25rem; border-radius: 50px; font-weight: bold; box-shadow: 0 4px 8px rgba(0,0,0,0.2); transition: opacity 0.5s ease; cursor: pointer;">Top</button>
<style>
#backToTopBtn.show {
display: block;
opacity: 1;
}
#backToTopBtn.hide {
opacity: 0;
}
</style>
<script>
window.addEventListener('scroll', function() {
const button = document.getElementById('backToTopBtn');
if (window.scrollY > 300) {
button.classList.add('show');
button.classList.remove('hide');
} else {
button.classList.add('hide');
button.classList.remove('show');
}
});
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
<\/script>