I am building a website which I am publishing with div
s. When I refresh the page after it was scrolled to position X, then the page is loaded with the scroll po
To reset window scroll back to top, $(window).scrollTop(0)
in the beforeunload event does the tricks, however, I tested in Chrome 80 it will go back to the old location after the reload.
To prevent that, set the history.scrollRestoration
to "manual"
.
//Reset scroll top
history.scrollRestoration = "manual";
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
You can do it using the scrollTop method on DOM ready:
$(document).ready(function(){
$(this).scrollTop(0);
});
For a simple plain JavaScript implementation:
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
The answer here(scrolling in $(document).ready
) doesn't work if there is a video in the page. In that case the page is scrolled after this event is fired, overriding our work.
Best answer should be:
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
This is one of the best way to do so:
<script>
$(window).on('beforeunload', function() {
$('body').hide();
$(window).scrollTop(0);
});
</script>
<script> location.hash = (location.hash) ? location.hash : " "; </script>
Put the above script in <head>
tag of your html. Not sure how single page apps behave! But sure works like charm in regular pages.