Explain Codes LogoExplain Codes Logo

How to scroll to top of page with JavaScript/jQuery?

javascript
scrolling
smooth-scrolling
vanilla-javascript
Alex KataevbyAlex Kataev·Feb 21, 2025
TLDR

Let's go Zero to Hero - use JavaScript and fire window.scrollTo(0, 0); to teleport to the top or go smooth and steady using jQuery: $('html, body').animate({ scrollTop: 0 }, 'smooth');. Both options are battleships that will get the job done.

Vanilla JavaScript and browser compatibility

When diversity is reality, our dear old friend document.body.scrollTop = 0 and his partner in crime document.documentElement.scrollTop = 0 are here to save the day, giving you a compatible solution for all browsers - including the ghost of Internet Explorer.

Scroll conservation post-reload

Got reload anxiety? No worries, history.scrollRestoration = 'manual' is the knight in shining armor that maintains scroll position on page reload. But beware, some vintage browsers may not support it. For these, use the trusty old setTimeout(function(){ window.scrollTo(0, 0); }, 0); as a fallback strategy.

Scroll on command

Ensure a tailored UX by allowing button or link-triggered scrolling. Use event listeners to teleport users to the top with a click:

document.getElementById('scrollBtn').addEventListener('click', () => { window.scrollTo({ top: 0, behavior: 'smooth' }); // "Up up and away!" });

Keeping it light without jQuery

Sometimes we prefer to travel light. In such cases, opt for vanilla JavaScript for a leaner codebase, sidestepping potential conflicts and keeping the page load light.

Advanced techniques and potential pitfalls

Scrolling that's smooth as butter

Amp up your glamour quotient with smooth scrolling. Bring in behavior: 'smooth', the JavaScript celebrity, for a silky scroll to the top.

Anchors aweigh

In case your 'top' is more dynamic, use a named anchor (<a name="top"></a>) to hit the exact bullseye on your scroll dartboard.

The art of continuous scrolling

If your case demands constant attention, let setInterval take the wheel. But remember, all good things must come to an end, and the interval needs clearing once you hit the top:

let intervalId = setInterval( () => { if (window.pageYOffset <= 0) clearInterval(intervalId); // "Alright, we're here. Everybody off." window.scrollBy(0, -50); }, 16);

Balancing user experience

Remember that sudden scrolls might spook users. So, keep it friendly and halt auto-scroll if the user attempts to manually scroll.

The jQuery advantage on page refresh

If team jQuery is your playground, use $(window).unload() to control scroll on page refresh. This will secure the scrolling fort when the document reloads.