0

I am trying to make a simple scroll down happen when the page is loaded.

@Route("somthing")
public class SomeView extends VerticalLayout{

public SomeView(){
    ...
    Adding some Elements
    ...

    UI.getCurrent().getPage().executeJs("window.scroll(0,300)");
}
}

I also tried adding a listener to the window:

 UI.getCurrent().getPage().executeJs("window.addEventListener('onload', function(){console.log('trigger');window.scroll(0,300);});");

But in both cases simply nothing happens when the page is loaded.

Tobias Nolte
  • 103
  • 2
  • 12
  • 3
    I'm assuming the second one doesn't trigger because the `window`'s `load` event has already fired at this point. – ollitietavainen Nov 06 '19 at 14:50
  • For another example of executing arbitrary JavaScript from the server-side of a Vaadin 14 app, see the Question, [*How to Print in Vaadin Flow?*](https://stackoverflow.com/q/58754154/642706) – Basil Bourque Nov 08 '19 at 07:27

2 Answers2

2

Like Olli mentioned in the comments, the second one doesn't work because the onload event has already happened at the time you add the eventlistener.

I believe the first one doesn't work because the SomeView was not attached yet to the page (as you execute the js in the constructor), therefore the page has not enough content to be scrollable yet.
You should execute that javascript in the onAttach method of the View.

@Route("somthing")
public class SomeView extends VerticalLayout{

    public SomeView(){
        ...
    }

    @Override
    public void onAttach(AttachEvent attachEvent) {
        UI.getCurrent().getPage().executeJs("window.scroll(0,300)");
    }
}
kscherrer
  • 5,486
  • 2
  • 19
  • 59
1

Just use getElement() instead of UI.getCurrent().getPage()

@Route("something")
public class SomeView extends VerticalLayout{

  public SomeView(){
    ...
    Adding some Elements
    ...

    getElement().executeJs("window.scroll(0,300)");
  }
}

in the contructor of your SomeView.

Meziane
  • 1,586
  • 1
  • 12
  • 22
  • @[tobias-nolte](https://stackoverflow.com/users/6044734/tobias-nolte): You are welcome. Thank you too – Meziane Nov 12 '19 at 09:54