Bug using window.scroll on Chrome

60 Views Asked by At

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?

1

There are 1 best solutions below

0
On

When you change your code to:

function backToTheTop() {
    let scrollListener = window.scrollY;
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });

    setTimeout(function () {
        if (window.scrollY !== 0) {
            console.log('timeout: '+window.scrollY+' ');
            backToTheTop();
        }
    }, 200);
}

Then you will see in de console.log something like:

timeout: 13564 
timeout: 2788 
timeout: 573 
timeout: 118 

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".