Search code examples
javascripthtmlcssresponsive-designresponsive

Changing orientation causing scrolling with requestAnimationFrame to "flicker"?


I am dealing with a website generated by a third party software, and I can't really change or remove any of the JavaScript that was generated. I have this problem where every time the user clicks on a navigation button or forgets a required field and clicks continue, the page automatically scrolls to the top. Right now I have this code that forces it to scroll back to whatever element is problematic (inspired by a stackoverflow answer but unfortunately I can't find it anymore :( will link it here if I find it)

    function scrollTo(element, timeMS=200, offset=0) {
        const elementPosition = element.offsetTop;
        const startPosition = scrollElementGlobal.scrollTop;
        const scrollDist = (elementPosition + offset) - startPosition;
        const startTime = performance.now();
        function scrollStep(timestamp) {
            const currentTime = timestamp - startTime;
            const scrollProgress = Math.min(currentTime / timeMS, 1);
            scrollElementGlobal.scrollTop = startPosition + scrollDist * scrollProgress
            // currentScroll = scrollElementGlobal.scrollTop
            if(scrollProgress < 1) {
                requestAnimationFrame(scrollStep)
            }
        }
        requestAnimationFrame(scrollStep)
    }

that I attach to the button with a click event that basically looks like this

continue_button.addEventListener('click', function() {
    if(something_went_wrong) {
        scrollTo(element_that_went_wrong)
        return;
    }
    
    if(something_else_went_wrong) {
        scrollTo(other_element_that_went_wrong)
        return;
    }
})

this works well on desktop, however on mobile it kinda breaks when the orientation change (first time clicking it will not animate and will automatically scroll back to the top of the page like the default behavior, and the second time it will scroll but the page will "flicker" since the user will see whatever is on top of the page for a split second). Any way I can fix this? Thanks!


Solution

  • Found the problem. There is another scrollTo function that was either from the browser or generated by the 3rd party software we use. Changed the function name to something else and the problem went away.