Force page scroll position to top at page refresh in HTML

纵饮孤独 提交于 2019-11-27 11:09:53

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

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 ofr 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 befor the unload of your page they will remember of 0,0 and won't scroll back to where the scrollbar was :)

You can also try

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

If you want to scroll at x position than you can change the value of 0 to x.

Check the jQuery .scrollTop() function here

It would look something like

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

Instead of location.reload(), simply use location.href = location.href. It will not scroll to the previous position as location.reload() does.

Note: This will not reload if there is any # in the URL

<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.

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);
});
$(document).ready(function(){
    $(window).scrollTop(0);
});

did not work for me as google chrome would just scroll back down after the page finished loading. What I used was

$(document).ready(function() {
    var url = window.location.href;
    console.log(url);
    if( url.indexOf('#') < 0 ) {
        window.location.replace(url + "#");
    } else {
        window.location.replace(url);
    }
});

// This loads the page with a # at the end. So it will always load at the top.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!