Scroll to top of the page
Scroll the window back to the top.
function goToTop() { window.scrollTo(0, 0); }
Usage
Markup
<div style="height: 3000px"></div>
Script
window.scrollTo(0, 1500);
goToTop();
window.scrollY; // → 0
Know the limits
- If the page sets scroll-behavior: smooth, the scroll animates. Keep smooth scrolling inside a prefers-reduced-motion: no-preference query.
- When the jump is a navigation step, also move focus, for example to the main heading, so keyboard and screen-reader users follow.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Scroll to top of the page from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.