0

I'm trying to reset browser scroll position on refresh and apparently it didn't work or ain't possible with modern browsers, am I wrong?

The code:

$(window).on('beforeunload', function() {
$('html, body').scrollTop($('#scroll-to-div-id-anchor').offset().top); });

Maybe I'm handling this incorrectly and there is another way to achieve that?

I tried all variations and possible options to this code, but it didn't work on Safari and Chrome (both on desktop and, especially - mobile).

1 Answers1

0

If you want the page to move to a certain element on reload, the expected behavior is to move the page to that point once it has been loaded. If you tried to move the page before it has been loaded, you won't know where you have to scroll to and if you tried to move it on unload, it's not guaranteed that that point will be saved once it's reloaded.

You can probably save the scroll location to the localStorage on unload and attempt to load the location onload, but in this case I would recommend just moving the page onload.

$(document).ready(function() {
  $('html, body').scrollTop($('#scroll-to-div-id-anchor').offset().top);
});
Chase Ingebritson
  • 1,559
  • 1
  • 12
  • 25
  • It won’t happen on load, because browser store final position (and restore it after reload) at the time user hit the reload button @Chase I –  Aug 28 '18 at 20:40
  • @AndrewK It should work just fine as long as you make sure to run the change after the document has been loaded. Can you include your HTML and an example of the implementation where this answer doesn't work? – Chase Ingebritson Aug 28 '18 at 20:45
  • This is exactly the point, it just didn’t, don’t know why, even on a “blank” test page, when reload is hit, position stays the same and not restore to original one as you can expect from the code (Safari/ Chrome). @Chase I, tested on a blank test page, I can add html later, on mobile now –  Aug 28 '18 at 20:54
  • Ok, sounds good. [This](https://stackoverflow.com/questions/7035331/prevent-automatic-browser-scroll-on-refresh#answer-31246298) answer may also hold some merit, but I don't have the environment set up to do the testing. – Chase Ingebritson Aug 28 '18 at 20:59