Friday, 24 February 2012

Displaying a DOM element using the SharePoint Dialog framework.

I have a webpart that is rendering information about people, including some extended information in a hidden div. The idea is, when the user clicks on the text "About me", extended information about the person (in the hidden div) is display using the SP.UI.ModalDialog framework.

I've used the SP.UI.ModalDialog framework a lot, and using it to display an application page, or a HTML string is easy. But what about sending it a DOM element that's been looked up within a script? In the MSDN documentation, the description of the html property of the options object is "A string that contains the HTML of the page that appears in the dialog." (SP.UI.ModalDialog.showModalDialog(options) Method). Nothing about sending a DOM element though.

It turns out (well, from the testing I did) that you can pass a DOM element into the html property. When you invoke the (javascript) function that opens the dialog, it all works fine, and the dialog window opens and displays the contents of the div... the first time anyway. The second time you call the function, you get a script error when trying to get a reference to the element.

It seems the element gets removed from the document object model after the first time the dialog is is used to display it (something I'm yet to understand why). To get around this, all I needed to do was clone the element, and pass the clone to the html property. Here's the function I used:

function imDisplayElementInPopup(elementId, title){
 //get the hidden element
 var wbalert = document.getElementById(elementId);
 //clone the element
 var wbalertClone = wbalert.cloneNode(true);
 ExecuteOrDelayUntilScriptLoaded(function () {
  //set the options
  var options = SP.UI.$create_DialogOptions();
  options.title = title;
  options.width = 270;
  //pass the cloned element into the html property
  options.html = wbalertClone;
 }, "sp.js");


  1. Hi Mathew I am facing problem while calling server side code for element available in HTML.

  2. Hi Suresh, what sort of problem are you encountering? The code in the example about is all client side.