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.

2
  • 3
    I'm assuming the second one doesn't trigger because the window's load event has already fired at this point. Commented Nov 6, 2019 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? Commented Nov 8, 2019 at 7:27

2 Answers 2

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)");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

@tobias-nolte: You are welcome. Thank you too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.