4

I'm trying to open or close a SharePoint Modal Dialog. The dialog opens one time, but it doesn't open in the second time, I just get a weird title only box. Also I cannot figure out how to close the dialog programmatically. Here is my code.

<button type=button onclick="openDialog()">click me</button> <div id="wrap" style="display:none"> <div id="d10"> my dialog message <button type=button onclick="closeDialog()">OK</button> </div> </div> <script> function openDialog() { var e = document.getElementById('d10'); var options = { title: "My Dialog Title", width: 400, height: 300, html: e }; SP.UI.ModalDialog.showModalDialog(options); } function closeDialog() { // HOW DO I CLOSE IT?! } </script> 

2 Answers 2

3

The correct way to close the dialog is to call the close function of the return value of SP.UI.ModalDialog.showModalDialog().

This code will open a dialog and then close it automatically after 2 seconds:

var options = { title: "My Dialog Title", width: 400, height: 300, html: e.cloneNode(true) }; var dialog = SP.UI.ModalDialog.showModalDialog(options); setTimeout(function(){ dialog.close() },2000) 
0
4

To answer the first question, you MUST either create or clone the DOM element that you pass to the showModalDialog, because MS deletes it when they are done with it (!)

To answer the second, to close a dialog there are two options. You can either simulate a click on the X in the corner of the dialog, or call the close method on the dialog.

For example (using JQuery)

 <button type=button onclick="openDialog()">click me</button> <div id="wrap" style="display:none"> <div id="d10"> my dialog message <button type=button onclick="closeDialog()">OK</button> </div> </div> <script> var mydialog; function openDialog() { var e = document.getElementById('d10'); var options = { title: "My Dialog Title", width: 400, height: 300, html: e.cloneNode(true) // <=== CLONED!! }; mydialog = SP.UI.ModalDialog.showModalDialog(options); } function closeDialog() { // EITHER METHOD 1 $('.ms-dlgCloseBtnImg').trigger('click'); // OR METHOD 2 mydialog.close(); } </script> 

This works for me, but it might not be the best way.

EDIT: changed to use close() per Daniel Stölzner

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.