Simple

Back-to-Top Button

A floating “back to top” button that appears once a visitor scrolls down and glides them back to the top on click — accessible, smooth, and library-free.

By Dillon LaGamma · HTML · CSS · JavaScript

The code

Drop the button markup anywhere in your page, then add the CSS and JavaScript below.

<button id="backToTop" aria-label="Back to top">&uarr;</button>

<style>
  #backToTop {
    position: fixed;
    right: 24px;
    bottom: 24px;
    width: 48px;
    height: 48px;
    border: none;
    border-radius: 50%;
    background: #017CFF;
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
  }
  #backToTop.is-visible {
    opacity: 1;
    pointer-events: auto;
  }
</style>

<script>
  const btn = document.getElementById("backToTop");

  window.addEventListener("scroll", () => {
    btn.classList.toggle("is-visible", window.scrollY > 400);
  });

  btn.addEventListener("click", () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  });
</script>

How it works

On scroll, we toggle an is-visible class whenever the vertical scroll position (window.scrollY) passes 400 pixels. The CSS fades the button in and out and uses pointer-events: none while hidden so it can't be clicked by accident.

The click handler calls window.scrollTo with behavior: "smooth" for a native smooth-scroll back to the top — no animation library required. The aria-label keeps it accessible to screen readers.

When to use it

Tune the 400 threshold to control how far down the page the button appears.