I am creating a website where I have to large content boxes that are absolutely positioned -- one at the top of the screen and one below off screen. I have the <body> element set to overflow-x and overflow-y none.
body {
overflow-x: hidden;
overflow-y: hidden;
}
When a button is clicked on the screen, the overflow-y changes to visible. This works just fine. However, if the user is near the bottom of the screen (as in farther down compared to when the page first loaded) and they reload the page, the user stays where they are but the overflow-y gets set to none and the user is stuck halfway down the page. Is there a way to have the user always start at the top of the page?
Also, this is completely vanilla js, html, and css -- no libraries or anything like that. If I need to add any other parts of my code let me know. Thanks
I have tried to use various methods of running code on load or before load (stuff like scrollTo(0,0) and the like). Having the page scroll before the reload works but does not look very good. It would be nice if it could just load at the top without the user actually seeing it move if that makes sense.
CodePudding user response:
You would need some javascript to get that done. I recommend the following:
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
CodePudding user response:
I found this solution on StackOverflow itself. Here is the solution
location.replace(location.href);
The above function replaces the URL with itself and then reloads the page, making the page start from the beginning. One disadvantage of this is, the previous History session for this page will also be replaced with a new one and the user won't be able to go back to the earlier pages using the back button on the browser. Check it here at MDN
Here is the link to the answer as well. (https://stackoverflow.com/a/65422431/10521908)
CodePudding user response:
It's a default behavior of browser's that they don't scroll to top on refresh. We have too manually do it.
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
For more refer this has the whole answer.
Note: Before posting a question, look if its already answered.