Explain Codes LogoExplain Codes Logo

Refresh Page and Keep Scroll Position

javascript
scroll-position
session-storage
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Mar 4, 2025
TLDR

To preserve the scroll position across page reloads, employ sessionStorage. Store the current Y position in the session before the refresh and then restore it afterward.

// Well, you're leaving? But let's remember where we came from! window.onbeforeunload = () => sessionStorage.setItem('scrollPos', window.scrollY); // Welcome back! We saved your spot. window.onload = () => window.scrollTo(0, sessionStorage.getItem('scrollPos') || 0);

This strategy is both concise and direct, particularly useful for maintaining UI state across page reloads.

More Tricks Up the Sleeve

When JavaScript Decided to Take a Day Off

What if JavaScript decided to call in sick and you find that it's disabled? Fret not, you can tack on the scroll position as a query parameter in your URL:

<a href="your-page.html?scroll=1000">Refresh</a>

Here's how to retrievement it using HTML with no JS intervention required:

<body onload="window.scrollTo(0, location.search.split('scroll=')[1])">

You see? Who needs JavaScript when you can fallback.

The jQuery Way

jQuery power users, we've got you covered! Let's cut to the chase:

// Packing bags before a journey? Don't forget to pack the scroll position! $(window).on('beforeunload', function() { var scrollPosition = $(document).scrollTop(); sessionStorage.setItem('scrollPos', scrollPosition); }); // Unpack your bag, scroll position first! $(window).on('load', function() { if (sessionStorage.scrollPos) { $('html, body').scrollTop(sessionStorage.getItem('scrollPos')); } });

And voila! A more readable jQuery-based approach!

Dealing with the Unpredictable: Dynamic Content

Got dynamic content that changes layout upon load? Worry not, refresh your memory after everything is rendered:

window.onload = () => { setTimeout(() => { // Let the dust settle, and find where you last stopped. window.scrollTo(0, sessionStorage.getItem('scrollPos') || 0); }, 100); // Adjust timeout as you see fit. };

A bit of patience can ensure consistency!

Bulletproofing Your Implementation

Keeping Session Storage Tidy

Session data kept too long? Clean up after yourself:

window.onload = () => { const savedPos = sessionStorage.getItem('scrollPos'); if (savedPos) { window.scrollTo(0, savedPos); // Housekeeping! Keep things tidy! sessionStorage.removeItem('scrollPos'); } };

This ensures your session storage remains efficient and privacy-friendly!

sessionStorage vs localStorage

sessionStorage is your friend for short-lived data. If a user springs up a new tab, it's a fresh start! Using localStorage can be handy but not for scroll position—just like an overplayed song, it can get old!

Manual Page Refresh with Scroll Position

Ever had to manually refresh a page and wish you remembered where you were? Well, have I got news for you:

function refreshPageWithScrollPosition() { var currentScroll = window.scrollY; // Reload with a breadcrumb trail! document.location.href = `your-page.html?scroll=${currentScroll}`; }

If sessionStorage isn't an option, make sure you leave a breadcrumb trail in the URL!

Conquer Every Mountain with scrollRestoration

For superior UX, leverage history.scrollRestoration:

if ('scrollRestoration' in history) { history.scrollRestoration = 'manual'; }

This helps maintain your scroll dominance, giving your script full authority over this realm!

Working with Hard Reloads

Sometimes, you may need a hard refresh:

window.onbeforeunload = () => { sessionStorage.setItem('scrollPos', window.scrollY); // Sometimes you have to be tough! document.location.reload(true); };

With this, you get a tailored experience even through hard cache-reloading times!

Be Compatible, Be Efficient

Don't over-rely on libraries. Performance and browser compatibility should be top of mind. Some techniques behave like teenagers—they just won't behave the same across all browsers.