0

I'm using this code in my Web app to go back a page:

window.history.go(-1);

It works well, but it takes users to the same vertical location they were on the page. After going back, how can I have the TOP of the page being shown instead?

I tried:

<script>
window.history.go(-1);
window.scrollTo(0, 0); // This doesn't execute.
</script>

I don't need smooth animations or transitions. The key is just making sure the command runs after going back.

GTS Joe
  • 3,612
  • 12
  • 52
  • 94
  • 3
    You need to call `scrollTo(0,0)` on page load of the page that is the target of the back click. – BenM Aug 11 '20 at 12:51
  • I tried that. But since users are being sent to the page on a history back, the page load is not triggering and the scrollTo(0,0) doesn't take effect. If it was a regular page load, that would work. – GTS Joe Aug 11 '20 at 12:55
  • what's the `return false;` for? – Argee Aug 11 '20 at 12:59
  • The DOMReady function should still fire, though. – BenM Aug 11 '20 at 13:00
  • @Argee Not needed, removed from my question. – GTS Joe Aug 11 '20 at 13:01
  • Does the user press any button to go back or simply the javascript handles it? If the user presses it, you could send them to link to a page which automatically takes them to top of the page rather than using a back button. – keidakida Aug 11 '20 at 13:08
  • hi, have you tried this https://stackoverflow.com/questions/2638292/after-travelling-back-in-firefox-history-javascript-wont-run/12648785#12648785 ? – h3nr1ke Aug 11 '20 at 13:13
  • @keidakida The JavaScript handles it automatically. It's a tricky question, I know. It looks easy, but the implementation is not straightforward. – GTS Joe Aug 11 '20 at 13:14

3 Answers3

1

Well, after trying several things these are the only two that worked for me.

jQuery

$(window).on("pageshow", function(event) {
    window.scrollTo(0, 0);
});

JavaScript

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

I hope it helps someone.

GTS Joe
  • 3,612
  • 12
  • 52
  • 94
0

This method works on Firefox though, not in Chrome. You can refer to this question After travelling back in Firefox history, JavaScript won't run for more details.

You can use this code in first_page.html:

<script>
    window.onunload = function () { };
    scrollTo(0, 0);
</script>

The onunload with make sure the scrollTo(0, 0) is executed even if the back button is pressed or even if you use window.history.go(-1);

keidakida
  • 713
  • 4
  • 12
0

Use history.scrollRestoration:

if (history.scrollRestoration) {
  history.scrollRestoration = 'manual';
}
history.back();

Profit!

scrollRestoration at MDN

Alex
  • 513
  • 5
  • 5