wicket 6: calling javascript function after page load
Asked Answered
M

2

6

This seems so simple, yet I cannot find an example of how to call javascript function from wicket, after the page is loaded (on page that extends WebPage). Can anyone give example on how to go that?

Monograph answered 20/6, 2013 at 9:52 Comment(1)
as noted in the question, the version of wicket is 6Monograph
C
21

You can have javascript do that for you

window.onload = function () {
// do stuff here
}

If you need parameters from your wicket page in the javascript function you can override renderHead and add the function there:

@Override
public void renderHead(IHeaderResponse response)
{
    super.renderHead(response);
    String bar = "something";
    response.render(JavaScriptHeaderItem.forScript("window.onload = function () {var foo='" + bar + "'}"));
    // or
    response.render(OnDomReadyHeaderItem.forScript("functionToCall(" + bar + ");") ;
}
Cutaneous answered 20/6, 2013 at 10:35 Comment(1)
tried "response.render(OnDomReadyHeaderItem.forScript("testAlert();")) ;" - works for me. thanks!Monograph
N
13

Yet another way to do that is to create AjaxEventBehavior as follows and add it to your page.

AjaxEventBehavior event = new AjaxEventBehavior("onload") {
    @Override
    protected void onEvent(final AjaxRequestTarget target) {
        // do stuff here
        target.appendJavaScript("alert('onload');");
    }
}
add(event);
Ninefold answered 21/6, 2013 at 20:21 Comment(4)
Can you add this to a component or does it have to be the page? Doesn't seem to fire when adding to a component...Accepted
appendJavaScript(), appends the mentioned function or the piece of the JS. When used in a Wicket function which is called repeatedly, the JS code gets executed multiple times and linearly increases.Overview
This solution in Wicket 8 seems not to work anymore.Trombidiasis
Is there alternative way for Wicket 8? @andpatKayekayla

© 2022 - 2024 — McMap. All rights reserved.