Scroll to Top

I’m trying to scroll to the top with code Components.button() .icon(icon) .styleName(CSSUtility.Common.BACK_TO_TOP) .onClick(buttonClickEvent -> layout.getElement().executeJs("window.scrollTo({top: 0, behavior: 'smooth'});")) .build()
. The JS script is from chatGPT. I see the buttons but it is not scrolling up. Please let me know what is wrong here
image.png

layout is VL here which is the parent

Also, how to disable this button when the user is already at the top

Timing issue, if you wrap the function in a setTimeout it should work. Or you use V24+ where a method for this exists / take a look at the source to see how it’s done there (also with setTimeout)

I’m already on V24. Let me google for setTimeout

Found something like this UI.getCurrent().getPage().executeJavaScript("setTimeout(function() { "+ " window.scrollTo({ top: 0, behavior: 'smooth' });" + "}, 500);"); But this is not working

It’s not a timing issue, since it’s executed when a user clicks ( so the page is rendered). Can you try to execute the JavaScript directly in your browser?

Why play with JS in an ugly way here?

layout.scrollIntoView()));

Or with animation:

    add(new Button("Scroll to top ", e -> {        ScrollOptions opts = new ScrollOptions(ScrollOptions.Behavior.SMOOTH);        layout.scrollIntoView(opts);    }));

This one worked. Thanks for this. I tried in a different way as UI.getCurrent().scrollIntoView(new ScrollOptions(ScrollOptions.Behavior.SMOOTH)) but that didn’t work. Any difference?

The beginning of the UI (the content frame) is already in the view, that probably contains the actual scrollable area (the layout variable in you case).