Back to Top

A Back to Top link helps users navigate to the top (start) of long pages.

<html id="start">
  <body>
    <!-- the contents of the page -->
    <a href="#start" id="back-to-start">Back to Top</a>
  </body>
</html>
function maintainBackToStartVisibility() {
  let backToStart = document.getElementById("back-to-start")
  if (backToStart) {
    let windowHeight = window.innerHeight
    let documentHeight = document.body.scrollHeight

    if (windowHeight * 1.5 < documentHeight) {
      backToStart.style.display = ""
    } else {
      backToStart.style.display = "none"
    }
  }
}

addEventListener("load", (event) => maintainBackToStartVisibility())
addEventListener("scroll", (event) => maintainBackToStartVisibility())
addEventListener("resize", (event) => maintainBackToStartVisibility())

References

  1. CSS-Tricks, Chris Coyier Need to scroll to the top of the page?
  2. Nielsen Norman Group, Back-to-Top Button Design Guidelines