Explain Codes LogoExplain Codes Logo

Force page scroll position to top at page refresh in HTML

html
scroll-position
page-refresh
browser-behavior
Alex KataevbyAlex Kataev·Oct 19, 2024
TLDR

JavaScript's window.scrollTo() readily navigates to the top on page load:

window.onbeforeunload = function() { window.scrollTo(0, 0); };

The snippet targets the onbeforeunload event making sure the scrolling resets prior to the page unloading, taking care of refresh cases.

Taking control of browser's automatic scroll restoration

Browser's history can interfere with scroll behavior. Overcome this by configuring the history.scrollRestoration attribute to "manual":

if ('scrollRestoration' in history) { history.scrollRestoration = 'manual'; // Because the force should be with you, not the browser! }

This restores your reign over scroll behavior during navigation, curtailing the browser's autonomy.

jQuery recipe to control page scrolling

If you are the jQuery aficionado, just attach the scrollTop(0) to the $(window).on('beforeunload') event:

$(window).on('beforeunload', function() { $(window).scrollTop(0); // jQuery to the rescue! });

It ensures that before the page signs off, its scroll position is reset, bringing jQuery's scrollTop to play.

The right way to use onbeforeunload event

Avoid common mishaps and ensure correct implementation of the window.onbeforeunload event:

window.onbeforeunload = function() { window.scrollTo(0, 0); /* Sherlock Holmes says "it's 'onbeforeunload', Watson not 'onbeforunload'" */ };

Trust the precise execution. Using setTimeout here may invite unpredictability due to the swift nature of the event.

Aiding consistent positioning amidst dynamic content

AJAX or SPAs can disrupt scroll positioning due to dynamic content loading. Remember to recalibrate top positioning after each content update. Here, window.scrollTo(0,0) comes into the picture post dynamic content load.

Tackling the heavyweight — Images and Media

Pages loaded with heavy media can offset scroll positioning. Ensure scroll-to-top execution post-load of all resources. Listening to window or image load events comes handy here.

Cross-browser compatibility — Check!

Different browsers have different takes on the onbeforeunload event. Ensure to test on multiple browsers and use feature detection techniques and polyfills for a universally compatible solution.