Saturday 1 November 2008

How to close (hide) a popup window produced by createPopup

Imagine a situation that you would like to build a menu and therefore you are using createPopup. Now you would like to model something like a menu in MS Excel 2007 where you have a multiple choice and therefore you have to have a button on the menu to be pressed when the selection is complete.

Traditionally the sub-window produced by createPopup will be closed if you press somewhere else. The same will happen if you trigger an action from that window like post back. Unfortunately none of those cases is acceptable for our scenario. The close() method called within that menu-window will produce a dialog asking whether the user would really like to close that window (which is not good for a menu).

Comment: the trivial search in Internet mostly give references to sites talking about popups produced by window.open

The following code should do the trick.

The menu will be produced on clicking on the first row/column cell of the table. The menu contains a combo and a button. The menu is produced by the test function: notice onclick="test(closeAction)" code calling it. Here we also pass as a parameter function that will be closing this window.
Now, in the test function we do
1. Produces the popup using createPopup
2. Assigns the closing function to the button onclick method
3. Store the reference on the popup in this window variable

The close action function consumes this variable and calls hide() .


<html>
<script language="javascript">
var mpopup

function test(clickEv)
{
var wnd= window.createPopup();
wnd.document.body.style.border="solid black 1px";
wnd.document.body.innerHTML="<select><option>a<option>b</select>
<br/><input id="'a1'" type="\">";
wnd.document.getElementById("a1").attachEvent("onclick",clickEv);

wnd.show(150,150,200,50,document.body);
mpopup=wnd;
}

function closeAction()
{
mpopup.hide()
}
</script>

<body>
<table>
<tr><th onclick="test(closeAction)">1kasdkjshd</th>
<th>1kasdkjshd</th><th>1kasdkjshd</th><th>1kasdkjshd</th>
<th>1kasdkjshd</th><th>1kasdkjshd</th><th>1kasdkjshd</th>
</tr><tr>
<td>1kasdkjshd</td><td>1kasdkjshd</td><td>1kasdkjshd</td>
<td>1kasdkjshd</td><td>1kasdkjshd</td><td>1kasdkjshd</td>
</tr><tr>
<td>1kasdkjshd</td><td>1kasdkjshd</td><td>1kasdkjshd</td>
<td>1kasdkjshd</td><td>1kasdkjshd</td><td>1kasdkjshd</td>
</tr></table>
</body> </html>


PS: It is useful to know that you can access objects from such popup window on the main document by using the following reference: parent.document.
getElementById('xxx')
,
where xxx is an id of the object you are accessing

No comments: