Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force page scroll position to top at page refresh in HTML

People also ask

How do you make a scroll to the top in HTML?

window. scrollTo(0, 0); …is a sure bet to scroll the window (or any other element) back to the top.

How do I scroll to the top of the page quickly?

Scroll one page at a time in all major browsers including Microsoft Internet Explorer and Mozilla Firefox by pressing the Spacebar key. Move back up the page by pressing Shift + Spacebar or the Home key on the keyboard.

How do you scroll to position in HTML?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

How do I change the scroll position to top in CSS?

If you want to set the scroll position of document. body , you can scroll the entire window altogether using window. scrollTo() ; it takes either a pair of coordinates (x,y) or an options object – if you just want to scroll nicely to the top, try window. scrollTo({top:0,behavior:'smooth'}); .


For a simple plain JavaScript implementation:

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

You can do it using the scrollTop method on DOM ready:

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

The answer here does not works for safari, document.ready is often fired too early.

Ought to use the beforeunload event which prevent you form doing some setTimeout

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

Again, best answer is:

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

(thats for non-jQuery, look up if you are searching for the JQ method)

EDIT: a little mistake its "onbeforunload" :) Chrome and others browsers "remember" the last scroll position befor unloading, so if you set the value to 0,0 just before the unload of your page they will remember 0,0 and won't scroll back to where the scrollbar was :)


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);
});

Check the jQuery .scrollTop() function here

It would look something like

$(document).load().scrollTop(0);