14

For instance, I open a web page, and scroll down to some position,

then I refresh the chrome browser, the browser could scroll the previous position again

How can I use javascript or css to let the browser to forget the scroll?

I have try $(window).scrollTop(0), but it doesn't work

hh54188
  • 14,887
  • 32
  • 113
  • 184

4 Answers4

30

It is resolved in the question below.

Disable brower's auto scroll after a page refresh?

// bypass auto scrolling.
if ('scrollRestoration' in history) {
  history.scrollRestoration = 'manual';
}
Brian Zhang
  • 421
  • 4
  • 4
  • This works, but required some extra tweaking for me. – nbrustein Dec 05 '18 at 12:10
  • 1
    this is so simple and it took 2 days to find out about scrollRestoration... thank you! – steven87vt Jul 13 '19 at 14:39
  • Works great! And all the major browsers now support it https://caniuse.com/?search=scrollRestoration – Gavin Aug 25 '22 at 13:00
  • this is the only correct solution, as the other ones will actually FORCE the browser to autoscroll to the position 0 after window is refreshed. and you might not want to do this, but instead scroll to your own computed position – user151496 Jan 12 '23 at 14:01
3

A simple way that I can say is to run this code on page load:

document.location = "#";

OR

window.scrollTo(0);

It set the browser viewport to the top of the page, again.

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
  • 4
    If I remember correctly, do `window.scrollTo(0)` on page load, and Chrome overrides your scroll. – John Dvorak Mar 12 '13 at 07:53
  • 2
    I meant even `window.onload` is too soon for `window.scrollTo`. Several miliseconds after `window.onload` should do, however. – John Dvorak Mar 12 '13 at 07:57
  • If I want the page scroll to left, not the top, what should I do? – hh54188 Mar 12 '13 at 13:44
  • 3
    Seconding @JanDvorak's findings. A `setTimeout` within window.onload works, but by then the window has already scrolled. – ericsoco Jun 04 '14 at 23:08
  • `window.scrollTo(0)` throws "cannot convert to dictionary" in Chrome and Firefox. Seems that you need to specify x and y like so: `window.scrollTo(0, 0)` – joe Apr 10 '21 at 05:18
2

Here is a clean way of getting this done.

window.addEventListener('unload', function(e){
   document.body.style.display = 'none';
});

By simply setting the body display to 'none' you don't have to worry about a flash of the browser scrolling to the top of the page before it is unloaded and the scroll position will automatically be reset to 0.

Walex
  • 79
  • 7
0

This worked for me :

JS Way:

window.addEventListener('unload', function(e){
window.scrollTo(0, 0)
});

Jquery way:

$(window).load(function() {
 $(window).scrollTop(0);
});
Harsha Vardhan Chakka
  • 1,357
  • 1
  • 9
  • 7