Why a long-page return control matters

On pages with a lot of content, a control that jumps back to the top saves the reader from a long manual scroll. That need shows up on single-page sites, with infinite scrolling, and on mobile devices where smaller viewports stretch the scrollable area. The usual pattern is a small control floating in a bottom corner. Building the click behavior in JavaScript is straightforward; the harder design problem is keeping the control low-profile while still giving a comfortable tap or click target.

The baseline takes very little code. Grab the button element, cache document.documentElement — the root element, needed to read offset values — in a variable:

var rootElement = document.documentElement

Register a click listener on the button:

function scrollToTop {
  // scroll to top logic
}

scrollToTopBtn.addEventListener("click", scrollToTop)

and implement scrollToTop with the scrollTo method:

function scrollToTop() {
  // Scroll to top logic
  rootElement.scrollTo({
    top: 0,
    behavior: "smooth"
  })
}

Then add some styling and place the button anywhere down the page, such as the footer. That alone produces a working control.

Threshold-driven visibility

A permanently visible button is easy, but hiding it until the reader has actually descended into the page is what makes it unobtrusive. The approach uses a scroll listener:

function handleScroll() {
  // Do something on scroll
}
document.addEventListener("scroll", handleScroll)

Every scroll invokes handleScroll. To turn raw scroll events into a meaningful threshold, compute the maximum scrollable distance in pixels. Two properties do the work:

  • scrollHeight: the height of an element including the portion hidden by overflow.
  • clientHeight: the inner height of an element in pixels, i.e., the visible portion.

Subtracting one from the other gives the total number of pixels the page can scroll:

var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

With scrollTotal in hand, dividing the amount already scrolled by that total yields a ratio from 0 to 1. Threshold logic can then turn the button on and off with any cutoff value; the demonstration uses 80% (a ratio of 0.80), an arbitrary figure. Values closer to 1 demand more scrolling before the button appears.

var rootElement = document.documentElement


function handleScroll() {
  // Do something on scroll
  var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight
  if ((rootElement.scrollTop / scrollTotal ) > 0.80 ) {
    // Show button
    scrollToTopBtn.classList.add("showBtn")
  } else {
    // Hide button
    scrollToTopBtn.classList.remove("showBtn")
  }
}


document.addEventListener("scroll", handleScroll)

Correct positioning once the button enters view is the job of the stylesheet:

.scrollToTopBtn {
  /* same general styles as before */
  
  /* place it at the bottom-right corner */
  position: fixed;
  bottom: 30px;
  right: 30px;


  /* keep it at the top of everything else */
  z-index: 100;


  /* hide with opacity */
  opacity: 0;


  /* also add a translate effect */
  transform: translateY(100px);


  /* and a transition */
  transition: all .5s ease
}


.showBtn {
  opacity: 1;
  transform: translateY(0)
}

The result: the button shows below the 80% mark and hides above it. The trade-off is performance. Keeping a listener on scroll means the current position is inspected continuously, which carries an overhead that can become costly on busy pages.

Handing the watching to the browser

The Intersection Observer API addresses exactly that overheard by delegating the monitoring to the browser, where it can be optimized. MDN's definition:

The Intersection Observer API provides a way to asynchronously observe changes for the intersection of a target element with an ancestor element or with a top-level document's viewport.

To apply the push-polling avoidance suggestion to a scroll-to-top button, make the utility itself the target:

// We select the element we want to target
var target = document.querySelector("footer");

The callback fires when that element "intersects" the viewport, i.e., when it comes into view. In this case the work inside the callback is simply adding or taking off a CSS class every time the footer enters or leaves the visible area. The callback receives an array of entries:

function callback(entries, observer) {
  // The callback will return an array of entries, even if you are only observing a single item
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // Show button
      scrollToTopBtn.classList.add('showBtn')
    } else {
      // Hide button
      scrollToTopBtn.classList.remove('showBtn')
    }
  });
}

Instantiate the observer with that callback:

let observer = new IntersectionObserver(callback);

Then start observing the selected target element:

observer.observe(target);

Visibility is now governed by intersections instead of scroll-bookkeeping, and the original problem is solved without polling scroll position.

Smooth motion via CSS

The jump back to the top can be animated, and modern CSS covers a fair share of this work.

<html id="top">
  <body>
     <!-- the entire document -->
     <a href="#top">Jump to top of page</a>
  </body>
</html>
html {
  scroll-behavior: smooth;
}

The behavior still needs care, accessibility improvements among them. The broader shape of the story is that capabilities that formerly required JavaScript are steadily migrating to CSS. The end product is a utility that is visible and usable without sitting on top of other page content.