Skip to content
jshacks.dev
Browser

Build a back to top button

Show a back to top button after the page scrolls, using an IntersectionObserver on a sentinel element and scrollTo with smooth behaviour.

1 min read
Summarize in AI

A back to top button should appear only after the reader has scrolled away from the top. A sentinel element at the top of the page and an observer avoid a scroll listener.

top.htmlHTML
<div id="top-sentinel"></div>
<button id="to-top" hidden>Back to top</button>
to-top.jsJavaScript
const sentinel = document.querySelector('#top-sentinel');
const button = document.querySelector('#to-top');

new IntersectionObserver(([entry]) => {
  button.hidden = entry.isIntersecting;
}).observe(sentinel);

button.addEventListener('click', () => {
  window.scrollTo({ top: 0, behavior: 'smooth' });
});

While the sentinel is visible the button is hidden. Once the reader scrolls and the sentinel leaves the viewport, isIntersecting becomes false and the button shows. The callback runs only on those two changes, not on every scroll tick.

scrollTo with behavior: 'smooth' animates the move, and browsers skip the animation for users who asked for reduced motion only if you check matchMedia('(prefers-reduced-motion: reduce)') yourself, or set scroll-behavior in CSS under a media query. A plain <a href="#top"> link needs no JavaScript and keeps working when scripts fail, so use the button only when you need the smooth movement. Keep it a real button with a visible focus ring. See scrollTo.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.