The problem
On a long page, scrolling all the way back to the top by hand is a minor but real annoyance — a back-to-top button that only appears once it’s actually needed (not cluttering the screen at the top of the page) is a small, well-understood pattern that’s still worth doing properly.
Expected outcome
By the end of this guide you will have a working button that stays invisible until it’s genuinely useful, then smoothly returns the reader to the top when clicked.
Requirements and costs
- Any website.
- Cost: free. No dependencies.
Step-by-step implementation
- Download the starter from the link below.
- Add one line to your page:
<script src="back-to-top.js"></script>. - That’s it — the script creates the button, positions it, and wires up the scroll listener and click handler automatically.
- Adjust
SHOW_AFTER_PXin the script if you want the button to appear sooner or later than 400px of scroll.
A real example
At the top of the page, the button is hidden. Scroll down 800px, and it appears. Click it, and the page smoothly scrolls back to position 0 — not an instant jump.
Verification and troubleshooting
What we tested, on 5 October 2026 (record TNT-TEST-2026-10-05-037): loaded a real demo page in a browser and confirmed the button’s display was “none” at the top of the page, became “block” after scrolling to 800px, and that clicking it correctly returned the page to scroll position 0 — all three real states confirmed in sequence, not assumed from reading the code.
Troubleshooting:
- The button never appears. Check your page is actually tall enough to scroll past
SHOW_AFTER_PX(400px by default) — a short page never triggers it, which is correct behavior, not a bug. - It appears immediately, even at the top. Make sure the script runs after the page loads normally (a plain script tag near the end of
<body>is fine) — running it before the page has its real height can misjudge the initial check. - You want it to match your site’s exact button style. The button’s look is one
style.cssTextline in the script — edit colors, padding and position directly there. - You want a fade-in/out transition instead of an instant show/hide. Add a CSS
transitiononopacityand toggle that instead ofdisplay— the script’s logic for deciding when to show it stays exactly the same either way.
Limitations and alternatives
This is a single fixed button in one corner of the screen; it doesn’t account for other fixed UI elements you might already have in that same corner (a chat widget, a cookie banner). If you have one, adjust the button’s position in the script so the two don’t overlap.
Free resources
The download contains the script and a working demo.
Download the back-to-top button (ZIP, 1 KB)
Is there a paid version?
Not applicable. There’s no meaningful paid version of a back-to-top button — this is the complete method.