Force page scroll position to top at page refresh in HTML
Asked Answered
D

17

182

I am building a website which I am publishing with divs. When I refresh the page after it was scrolled to position X, then the page is loaded with the scroll position as X.

How can I force the page to be scrolled to the top on page refresh?

  • What I can think of is of some JS or jQuery run as onLoad() function of the page to SET the pages scroll to top. But I don't know how I could do that.

  • A better option would be if there is some property or something to have the page loaded with its scroll position as default (i.e. at the top) which will be kind of like page load, instead of page refresh.

Densitometer answered 8/9, 2010 at 3:7 Comment(2)
Surprisingly, none of the solutions here worked for me, but this one did: https://mcmap.net/q/137665/-reload-browser-does-not-reset-page-to-topMerrymaking
I came here because I want the opposite behavior of what @Densitometer is asking for. EMACS impatient-mode keeps sending my web browser to the top of the document when I type new text into a buffer. This is disorientating and I wish I could make EMACS impatent-mode stop doing that.Sande
P
191

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

$(document).ready(function(){
    $(this).scrollTop(0);
});
Pinsk answered 8/9, 2010 at 3:15 Comment(1)
Does not work on Safari. But this -> https://mcmap.net/q/137666/-prevent-automatic-browser-scroll-on-refresh does.Regret
B
258

For a simple plain JavaScript implementation:

window.onbeforeunload = function () {
  window.scrollTo(0, 0);
}
Breadth answered 10/11, 2014 at 6:12 Comment(10)
@Paul12_ - I just tested it on Safari 11.0.3 and works okay for me, which one are you using?Breadth
This did not work for me. I had to return from the onbeforeload function to make it work.Consensus
@Consensus -- what did you return?Breadth
This throws the following error in Chrome: Uncaught TypeError: Failed to execute 'scrollTo' on 'Window': parameter 1 ('options') is not an object.Poco
@OGSean - could I have a look at the exact excerpt of the code you wrote? You can give me pastebin link.Breadth
adding document.querySelector('html').style.scrollBehavior = ''; may be necessary too. If it was set to smooth, it might not get to the top before the page reloads.Binkley
@OGSean - Try window instead of WindowPrefix
Doesn't work on FirefoxMaggiemaggio
@LenkaPitonakova - can share the code you are using? works on my end...Breadth
@ProfNandaa strange, I just copy-pasted the one in the answer. I'm on a Mac if that helps.Maggiemaggio
P
191

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

$(document).ready(function(){
    $(this).scrollTop(0);
});
Pinsk answered 8/9, 2010 at 3:15 Comment(1)
Does not work on Safari. But this -> https://mcmap.net/q/137666/-prevent-automatic-browser-scroll-on-refresh does.Regret
R
39

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);
});
Regret answered 26/4, 2014 at 15:5 Comment(2)
Add after scroll function : $('html').text(''); ,so stroller will be resetPitcher
@Userpassword Don't you think $("html").remove() would be better ?Regret
J
31

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);
});
Jennette answered 2/4, 2020 at 14:40 Comment(2)
This is the best response for me, works on Chrome/LinuxTimothytimour
This was great. In multi-page case, just added the two lines history.scrollRestoration = "manual"; and $(window).scrollTop(0); to the js function right after I make the second page visible.Battista
W
30

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 :)

Widely answered 7/9, 2016 at 12:42 Comment(1)
@Paul12_ Safari requires document.documentElement.scrollTop to work. I typically use both though.Metalline
C
13

The JS history API has the scrollRestoration property, which when set to manual, prevents the last scroll location on the page to be restored:

if (history.scrollRestoration) {
    history.scrollRestoration = 'manual';
} else {
    window.onbeforeunload = function () {
        window.scrollTo(0, 0);
    }
}
Cookie answered 26/4, 2021 at 14:26 Comment(2)
This is a great answer, you can even simply use the history.scrollRestoration = 'manual'; oneliner if you're working on a project where you know the browser will support it.Abrahan
Thanks, changing to one liner might make a difference if you are using SSR and window is not available.Cookie
C
11

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.

Commonable answered 29/5, 2013 at 4:53 Comment(0)
C
10

Check the jQuery .scrollTop() function here

It would look something like

$(document).load().scrollTop(0);
Cataclysm answered 8/9, 2010 at 3:15 Comment(0)
E
7

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

Embargo answered 12/1, 2017 at 16:17 Comment(0)
H
5
<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.

Hetrick answered 26/1, 2016 at 22:47 Comment(0)
F
4
$(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.

Fulton answered 18/8, 2016 at 9:54 Comment(0)
C
4

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);
});
Clyde answered 12/1, 2017 at 12:12 Comment(0)
B
3

I found that these CSS styles force the page to always scroll to top on reload/refresh:

html {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

body {
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
    width: 100%;
}
Bootery answered 9/12, 2020 at 17:20 Comment(1)
Can confirm that this works. Would love if someone could get an explanation but nevertheless, this should be 2nd highest answer (above all those very, very repetitive .scrollTop(0)s),Rodl
G
2

This is one of the best way to do so:

<script>
$(window).on('beforeunload', function() {
  $('body').hide();
  $(window).scrollTop(0);
});
</script>
Gefen answered 22/10, 2020 at 16:48 Comment(0)
A
2

You can use location.replace instead of location.reload:

location.replace(location.href);

This way page will reload with scroll on top.

Absher answered 23/12, 2020 at 10:5 Comment(1)
This seems to work, but I can't find documentation to explain why it works. If anyone has that, please share!Arthromere
M
1

you can use it it your html page to as:

history.scrollRestoration = "manual";

$(window).on('beforeunload', function(){
    $(window).scrollTop(0);
});
Moray answered 25/11, 2022 at 8:58 Comment(2)
Can you please explain what your code is doing and why this works? Seems legit, but you will want to explain this more for other readers.Causeuse
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Bertberta
T
0

The supercalifragilisticexpialidocious answer is:

add this at the top of your js file or script tag

document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

document.body.scrollTop = 0; // For Safari
Tonicity answered 30/8, 2019 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.