Floating Scroll-to-Top Button That Only Shows on Scroll

This is a scroll-to-top button that appears when the user scrolls down the page and disappears automatically after 5 seconds of inactivity. If the user returns to the top of the page, the button hides immediately.

HTML

<a href="#" class="scroll-top d-flex align-items-center justify-content-center">
  <i class="fa-solid fa-arrow-up"></i>
</a>

CSS

/* ===============================
       Scroll-to-Top Button
================================ */
.scroll-top {
  opacity: 0;
  visibility: hidden;
  position: fixed;
  top: 50%;                    /* Vertically centered */
  right: 30px;                 /* Positioned 30px from the right edge */
  transform: translateY(-50%); /* True vertical centering */
  z-index: 1000;
  width: 40px;
  height: 40px;
  background: var(--color-button);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease, visibility 0.3s ease;
}

.scroll-top.show {
  opacity: 1;
  visibility: visible;
}

JAVASCRIPT

<script>
  const scrollButton = document.querySelector('.scroll-top');
  let scrollTimeout;

  function handleScroll() {
    if (window.scrollY > 100) {
      // Show the button when the user scrolls down
      scrollButton.classList.add('show');

      // Clear any previous timeout
      clearTimeout(scrollTimeout);

      // Hide the button after 5 seconds of no scroll activity
      scrollTimeout = setTimeout(() => {
        scrollButton.classList.remove('show');
      }, 5000);
    } else {
      // Hide the button when scrolled back to the top
      scrollButton.classList.remove('show');
    }
  }

  window.addEventListener('scroll', handleScroll);

  // Scroll smoothly to the top when the button is clicked
  scrollButton.addEventListener('click', function (e) {
    e.preventDefault();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });
</script>

1 Like