Wicket ModalWindow: click outside modal to dismiss
-
27-10-2019 - |
Question
I need to add a behavior to ModalWindow
such that when a user clicks outside of the modal, if a certain condition is met (checked server-side in my respond()
method), the modal is dismissed.
I tried implementing something based on this answer. The problem is that I can't attach a click listener to the modal window div because it's not added to the DOM until the modal is shown (the example attaches a keyup
to the document itself.)
I thought of extending ModalWindow
and adding the JS via getShowJavascript()
, but then I don't have any means to connect it to an AbstractDefaultAjaxBehavior.respond()
method for the test.
Solution
I solved this by adding the behavior not to the modal, but rather to the widget I add to the modal via ModalWindow.setContent()
. When my widget is added to the modal, the mask div is present in the DOM, and I can then successfully attach a click handler.
To wit:
public static class CloseModalOnOutsideClickBehavior extends AbstractDefaultAjaxBehavior
{
private final ModalWindow modal;
public CloseModalOnOutsideClickBehavior(ModalWindow modal)
{
this.modal = modal;
}
@Override
protected void respond(AjaxRequestTarget target)
{
if (myConditionIsMet()) modal.close(target);
}
@Override
public void renderHead(IHeaderResponse response)
{
response.renderJavascriptReference("http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js");
response.renderJavascript("" +
"$(document).ready(function() {\n" +
" $('div.wicket-mask-dark').bind('click', function(evt) {\n" +
getCallbackScript() + "\n" +
" evt.preventDefault();\n" +
" });\n" +
"});", "closeModal");
}
}
Note that I'm somewhat precariously depending on the modal window's mask having a class named "wicket-mask-dark"; this may not be the case if you alter the CSS settings used by ModalWindow
.