
Richard C.
—How do you scroll to the top of the page in JavaScript? You might want to do this programmatically to, for example, add a button to the bottom of the page that a user can click to immediately return to the top.
If you want to move the page to a specific coordinate programmatically the best solution is to use scrollTo:
globalThis.scrollTo({ top: 0, left: 0, behavior: "smooth" });
Note:
globalThis instead of window because globalThis works in both Node.js and browsers, instead of global or window.behavior can be smooth, instant, or auto (which is set in CSS). smooth is best for most web pages, but for work apps where users might scroll up hundreds of times a day you’ll want to use instant.top and left are the number of pixels away from the top left corner of the page.globalThis.scrollTo(0, 0);. There’s no reason to use this anymore, but it isn’t harmful.If you want to scroll the page to a specific section, where the absolute coordinate might change as the page layout changes, it’s better to use an anchor.
document.getElementById("title").scrollIntoView({ behavior: "smooth" });
You need an element with an id for this to work, like <span id="title">This is the top of my page</span>.
Instead of scrolling automatically, if you want the user to be able to click a button to scroll up, you can add the following to your HTML:
<span id="title">This is the top of my page</span> <button onClick="document.getElementById('title').scrollIntoView({ behavior: 'smooth'});"> Back to top </button>
Be careful if you change the location of the URL bar, like this: document.location.href = "#top";. It may cause problems in a single page app (SPA) if it interferes with the framework’s page history. Test it and see.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
