2

I have a problem in vanilla JS that has been asked in slightly differing forms on this site, but there doesn't seem to be an answer for vanilla javascript? I would like the page to appear at the top on reload / refresh using vanilla JS (without any scrolling back up to the top with scrollTop()).

I've checked these questions and the related answers:

Prevent automatic browser scroll on refresh

Force page scroll position to top at page refresh in HTML

Prevent automatic browser scroll on refresh

The problem is there are two vanilla JS answers scattered in these questions, one of which doesn't work in IE/Edge, the other one doesn't work in Safari

Doesn't work in Safari:

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

Doesn't working in IE / Edge

history.scrollRestoration = "manual";

Surely there must a way of getting a page to appear at the top on refresh / reload?

Also I can't have it scroll up to the top on reload / refresh so any scrollTop() related answers aren't applicable.

Many thanks in advance

pjk_ok
  • 618
  • 7
  • 35
  • 90

1 Answers1

0

You can always just add some flags to include both solutions:

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

and

if(history && history.scrollRestoration) history.scrollRestoration = "manual";

Also I can't have it scroll up to the top on reload / refresh so any scrollTop() related answers aren't applicable.

also why?

Abana Clara
  • 4,602
  • 3
  • 18
  • 31
  • I can't have scrollTop() because there is a relatively complex animation that just looks silly as the page scrolls back up because you miss the start of it. Also I can't use your answer because the `.onbeforeunload` property causes unwanted behaviour in Safari — the page scrolls down to the previous point after loading. Thanks for taking the time to answer though. – pjk_ok Aug 20 '18 at 12:33
  • Which is why we add both solutions to compensate. Also you can call the line during `.onload`. – Abana Clara Aug 20 '18 at 14:20