13

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,027
  • 31
  • 107
  • 178

4 Answers4

24

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
  • 361
  • 2
  • 4
4

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
  • 30,654
  • 27
  • 127
  • 194
  • 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);
});