views:

884

answers:

2

Can anyone provide a clean example of how to use JQUERY's UI Modal dialog. Surprisingly it's not as simple as you would think.

Goal:

  1. clicking an element loads a modal

  2. The modal appears showing "Loading..." And then makes an ajax call to get the contents of the modal

  3. The modal can be closed by clicking a close btn or by pressing escape

  4. The modal can be repopened, and when it's reopened it doesn't show the state of the previous modal interaction.

Thanks!

Here is what I currently am doing, but it works very clumsy and doesn't seem at all like a smart solution. Ideas?

var $dialog = $('<div id="sharerdialog"></div>')
.html('<p>Loading...</p>')
.dialog({
    autoOpen: false,
    title: 'Share the item',
    position: ['center',150],
    width: 450,
    focus:function(event, ui) {
        $('#dialogcloser').click(function() {
            $dialog.dialog('close');
        });
    }, 
    open: function(event, ui) {
        var title2use = document.title;
        title2use = escape(title2use);          
        $("#sharerdialog").load("/items/ajax/share/index_beta.cfm?itemid=#itemID#&itemtitle=" + title2use);
    }
});
// Bind the Share btn to Open the Modal
$('#itemshare').click(function() {
    $dialog.dialog('open');
});
A: 

The main problem I see with your code, is that you are not adding the dialog to the DOM, therefore, the browser won't display it. My suggestion is that you first try:

var $dialog = $('<div id="sharedialog"></div>')
      .html('<p>Loading....</p>')
      .appendTo('body')
      .dialog({...});

So that you added it to the DOM, and the browser can display it.

UberNeet
Interesting, the code above is working just fine, it just seems real clunky.
AnApprentice
From a UI perspective, it might get annoying to see a modal every time you make a request. Since you mentioned the user can close it, I assume you just want to give the user feedback that the response is being loaded. In that case, why don't you just simply show the `Loading...` text (or icon), close to the button, or as a top layer over the result area. Use css `visibility: hidden;` or `display: none;` and show/hide it using jQuery.
UberNeet
Interesting idea.
AnApprentice
A: 

At the risk of being slaughtered for shameless self-promotion, I have two articles written that introduce the jQuery UI Modal and look at some of the tricky bits. It may or may not be of use, but it does take a simple perspective.

Phil.Wheeler