Reputation: 4152
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.
Upvotes: 1
Views: 1984
Reputation: 553
Use history.scrollRestoration:
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
}
history.back();
Profit!
Upvotes: 0
Reputation: 4152
Well, after trying several things these are the only two that worked for me.
$(window).on("pageshow", function(event) {
window.scrollTo(0, 0);
});
window.onpageshow = function(event) {
window.scrollTo(0, 0);
};
I hope it helps someone.
Upvotes: 1
Reputation: 741
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);
Upvotes: 0