Navigation to new page: new page not scrolled to top but same position as p

Hi,

We use server side navigation like this

getUI( ).ifPresent( ui → {
ui.navigate( Test.class );
} );

We have notified that if the previous page was scrolled to the bottom, the new page is also scrolled to the bottom.
We want to have all new pages scrolled to the top of the page. How can we achieve this in vaadin flow?

Kind regards

Hi Bart

This probably happens because your two Views have the same parent layout, which will not be reattached to the dom upon Router Navigation. Therefore, if the scrolling was done on an element of the parent layout, that scrolling status remains after navigation. If the scrolling action happened on an element of the childview, the scrolled element will be detached and the second view will not be scrolled down when navigating.

So you could do one of the following to change this behaviour:

  • Refactor your main view so any scrolling will not scroll the elements of the mainview but scrolls only the content instead (the routed view). (There are cases where scrolling on the parent layout is desired. If this is the case, do the other suggestion)
  • Whenever a routed View is attached to the DOM, fire an event that scrolls to the top of the page. This is basically a workaround. addAttachListener(event -> // execute js scroll to top);

I literally just saw a customer ticket on the same topic. Thanks Kaspar.

This should really be the default behavior when a navigation event occurs.

Thanks for the help.
We’ve solved the problem with the workaround.

Kind regards

Martin Israelsen:
This should really be the default behavior when a navigation event occurs.

I disagree, because it would be unnecessary execution of javascript in most cases.

Kaspar Scherrer:

Martin Israelsen:
This should really be the default behavior when a navigation event occurs.

I disagree, because it would be unnecessary execution of javascript in most cases.

It probably depends on the app and layout. I think all my pages on mobile scroll and my navigation buttons are at the bottom, so I’d have to execute the code after all navigation events to make sure that I’m at the top.

My comments was not that Vaadin should execute the JS from the Java side, but rather that the frontend should do this automatically or have a setting that could be turned on that would cause it to scroll to the top after a navigation event.

Bart Ramaekers:
Thanks for the help.
We’ve solved the problem with the workaround.

Kind regards

Hello,

do you have a more specific code example of how you solved the problem?

Hi Hakan,

We have overwritten the ‘BeforeEnter(BeforeEnterEvent event)’ and added

getElement( ).executeJs( “window.scrollTo(0,0)” );