I am using below code at onLoad to go to top of page. window.scrollTo(0,0) in Javascript it's working for browsers but not on any of the MOBILE Devices.
Asked
Active
Viewed 8,407 times
1 Answers
1
There are quite a few articles about the "window.scrollTo(0,1) fix" for mobile pages. Using a magic number for timeout can be frustrating for the user. Content starts to appear, and the user begins to scroll down the page and consume the information, and then getting snapped back up to the top of the page. A better approach would be something like this:
window.addEventListener("load", function() {
setTimeout(function() {
var scrollPos = window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// seems like the author of linked code source had a logic bug here
// if you need to apply this, probably you will want to check scrollPos > 1
// I keep the comment above - although it is wrong. You should
// not scroll, once the user already interacted with the page.
// For further information, see the linked article below.
if (scrollPos < 1) {
window.scrollTo(0,1);
}
}, 0);
});
For further information - here is one article (script comes from there)

axel.michel
- 5,764
- 1
- 15
- 25
-
1window.scrollTo(0,1); doesn't work for mobile devices even if you put addEventListner/setTimeOut. Instead of this I used angular functionality to scroll to ID which is anchor scroll. Below code works for me. ..... Inject $location,$anchorScroll,$timeout,$location dependencies to work. .... $timeout(function () { $location.hash("give id name here to scroll to"); $anchorScroll(); }); – MaxWorld Jan 30 '16 at 01:20
-
1@pocketrocket If you read the related article, the < 1 is wanted. He wrote: "Why get the scroll position of the page first? Because we can use that value to see if the user has started to scroll down the page. If the scroll position is less than 1, we can assume the user hasn’t started scrolling, and can thus snap the user to (0,1). Otherwise, there’s no need to snap to that position, because the user has already started engaging with the page and is past it." So the code was as wanted, your fix is exactly that kind of interaction with the user behavior that should be avoided. – axel.michel Jul 11 '20 at 13:16