scrollTo() works in Preview but not on Live site

I was hoping someone could help me work out why scrollTo() is working in preview but not on the live site for me. I’ve posted this question before but haven’t resolved it yet, or had a response from Wix.

I’ve written some custom code to scroll back to the place on the home page that the user was at when they followed a link away, as it doesn’t seem to do this by default.

On the click of an image on the home page I store the X and Y coordinates into the session and then I redirect away to the page related to that image:

session.setItem("scrollX", event.pageX);
session.setItem("scrollY", event.pageY);
wixLocation.to("/somepage");

When the visitor hits back (to return to the home page) the following onReady code fires;

$w.onReady(function () {
 
 let scrollX = Number(session.getItem("scrollX"));
 let scrollY = Number(session.getItem("scrollY"));
 
    console.log("X: "+scrollX);
    console.log("Y: "+scrollY);

    console.log("Page: trying to scroll to: "+scrollX+', '+scrollY);
    setTimeout(function () {wixWindow.scrollTo(scrollX, scrollY),2500});
    session.removeItem("item");
    session.removeItem("scrollX");
    session.removeItem("scrollY");

});

The console on the live site echo’s the console logs as expected, however the scroll just doesn’t occur;

X: 755                                                  console.js:35
Y: 5922                                                 console.js:35 
Page: trying to scroll to: 755, 5922                    console.js:35

Here is a video to show if i haven’t explained it well;

Why did you add the timer? 2.5 seconds seems a little excessive. Maybe you could remove the timer and use an async function instead. i.e.

$w.onReady(async function() {
    let scrollX = await Number(session.getItem("scrollX");
    let scrollY = await Number(session.getItem("scrollY");
    wixWindow.scrollTo(scrollX, scrollY);
}

Thanks for your reply David

I added the timer to test and see if it was an issue with the page not fully loading prior to the function executing.

Thanks for the async suggestion. I’ve made those changes (inc removing the timer) however it hasn’t resolved the issue.

@jamie Then maybe scrollTo can’t resolve on page load for some reason then. You could add it in a viewportEnter event listener for the first strip/element on your page perhaps.

@skmedia Thanks so much for this suggestion. I added the code to the viewportEnter event for an anchor and it now works as expected.

Thanks again!