I'm facing an issue with Google Chrome and Edge browsers when using
window.scroll({
top: 0,
behavior: 'smooth'
});
The problem is that it doesn't always scroll to the top of the page; most of the time, it scrolls a portion and stops. This issue occurs on Google Chrome and Edge, and I'm using the latest version of Chrome (Version 21.0.6167.140 (Official Build) (64-bit)). In Firefox, the problem doesn't occur.
To work around the issue, I came up with the following solution:
function backToTheTop() {
let scrollListener = window.scrollY;
window.scrollTo({
top: 0,
behavior: 'smooth'
});
setTimeout(function () {
if (window.scrollY !== 0) {
backToTheTop();
}
}, 200);
}
While this resolved the initially mentioned problem, it introduced other issues, such as slow scrolling on mobile browsers or the site continuing to scroll even if the user scrolls down while it is going up.
Has anyone encountered a similar problem and knows how to resolve it?
When you change your code to:
Then you will see in de console.log something like:
May I conclude that your function
backToTheTop()
is started multiple times?Leave out the
setTimeout
, and investigate more why your original script "does not alwaus go to the top of the page".