Scroll to top javascript code only working in editor

Hi all,

I have back/next buttons that are at the bottom a page. When the buttons are clicked, in addition to performing logic used to modify/display data, I want the page to be scrolled to the top.

I am running the following js in the workflows for both buttons:

const node = wwLib.getFrontDocument().getElementById("topofpage");
const yourHeight = 0; 

node.scrollIntoView(true);

const scrolledY = window.scrollY;

if (scrolledY) {
  window.scroll(0, scrolledY - yourHeight);
}

This “topofpage” id definitely exists (it’s the id of the first div on the page), and clicking on the buttons does scroll to the top of the page when I view it in the editor. When I publish my site, the scroll to top doesn’t work. I have tested on both Chrome and Firefox.

Given the code is running as part of button click event, I wouldn’t have thought there would be any risk of the elements not being loaded yet.

Any ideas where I may be going wrong here?

For reference, you can see one of the button workflows below (the fw_ScrollToTop workflow just has the js code shared above).

Thanks!

Hi,
when you say it does not work does it means you have an error happening on the console, or that the scroll is wrong? Or nothing happened?

Thanks @aurelie. I mean that the application doesn’t scroll at all - basically the same behaviour as if that workflow didn’t exist.

If it helps, I have found a workaround which is to use the following code instead:

window.scrollTo({ top: 0, behavior: 'smooth' });

This is working in the editor and live site, and I guess for my purposes I don’t need a resolution to this question anymore. I’m still curious though as I suspect the answer may have broader applicability that will be helpful elsewhere…

1 Like