Force page scroll position to top at page refresh in HTML
JavaScript's window.scrollTo()
readily navigates to the top on page load:
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":
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:
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:
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.
Was this article helpful?