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.
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.
<div id="top-sentinel"></div>
<button id="to-top" hidden>Back to top</button>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.