Search code examples
sharepoint-2010modal-dialogpageload

How to display a simple dialog in SharePoint 2010 without breaking the page?


I've worked on this for several hours today and am getting no where. Hoping someone can step in and please help.

All I want to do is display a simple message in a pop up dialog to tell users of some changes coming to a SharePoint 2010 site. I never thought this would be so difficult!

I've gone through a dozen links from a Google search but nothing has helped.

The only thing that sort of works is this code that I put into a Content Editor Web Part:

<script type="text/javascript">
    function codeAddress() {
        alert('ok');
        var options = {

            Title: "Survey",

            height: 500

        };
        _spBodyOnLoadFunctionNames.push("codeAddress");
    }
    window.onload = codeAddress;
</script>

But, the problem with this code is that after I click Ok, the page behave strangely. The java script of the page does not work, and even editing the page is messed up until I delete the webpart with the code.

I suspect that the problem has to do with this:

_spBodyOnLoadFunctionNames.push

But if I remove it then the pop up does not work.

In case it's not clear, my goal is to show any type of dialog in which I can type a sentence or two to tell the user something. Then they can click OK and give full control back to the page.

Please please someone help!


Solution

  • Shame on Google for not leading you directly to SP.UI.Modal.Dialog.showModalDialog().

    <script>
    ExecuteOrDelayUntilScriptLoaded(showDialog,"sp.js");
    
    function showDialog(){
        var options = SP.UI.$create_DialogOptions();
        options.title = "My Amazing Dialog Box";
    
        // create a dummy HTML element for the body of your dialog box
        var div = document.createElement("div");
        div.appendChild(document.createTextNode("Some text inside my dialog box."));
        options.html = div;
    
        SP.UI.ModalDialog.showModalDialog(options);
    }
    </script>
    

    If you want to put that in a content editor web part:

    1. Save the above code into a text file
    2. Upload that text file to a document library on your site
    3. Add a content editor web part to the page where you want the dialog to appear
    4. Edit the web part, opening up the web part properties panel on the side of the screen
    5. Paste the URL of the text file that you uploaded into the "Content Link" property

    This method prevents SharePoint from stripping your JavaScript out of the content editor web part, and lets you use that same script on multiple pages.