Coder Perfect

In HTML, force the top of the page to scroll when the page is refreshed.

Problem

I’m working on a website that will be published using divs. When I refresh the page after scrolling to position X, it loads with the scroll position set to X.

On page refresh, how can I compel the page to scroll to the top?

Asked by Moon

Solution #1

For a straightforward JavaScript implementation, see:

Answered by ProfNandaa

Solution #2

You may achieve it with DOM ready’s scrollTop method:

$(document).ready(function(){
    $(this).scrollTop(0);
});

Answered by Pat

Solution #3

The solution given here does not work on Safari because document.ready is frequently fired too early.

You should use the beforeunload event to avoid having to do any setTimeout.

$(window).on('beforeunload', function(){
  $(window).scrollTop(0);
});

Answered by Ben

Solution #4

Again, the ideal response is:

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

(That’s for non-jQuery; if you’re looking for the JQ way, look it up.)

EDIT: It’s “onbeforunload” instead of “onbeforunload”:) Chrome and other browsers “remember” the last scroll position before unloading, thus if you set the value to 0,0 immediately before your page unloads, they will remember 0,0 and will not scroll back to where the scrollbar was:)

Answered by xoxel

Solution #5

To return to the top of the window, press $. (window). The secret is to use scrollTop(0) in the beforeunload event, but when I tested it in Chrome 80, it went back to the old place after the reload.

Set the history to prevent this. scrollReturn to “manual” mode.

//Reset scroll top

history.scrollRestoration = "manual";

$(window).on('beforeunload', function(){
      $(window).scrollTop(0);
});

Answered by Alex Having Fun

Post is based on https://stackoverflow.com/questions/3664381/force-page-scroll-position-to-top-at-page-refresh-in-html