Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Dialog behaves unpredictably

The jQuery UI dialog drives me up the walls. To the best of my understanding, here's how it works:

When you do $('#myDialog').dialog({...}), it copies the #myDialog element and moves it inside this bizarre widget thing at the bottom of your body tag. This is crazy! It will duplicate possibly unique DOM elements (with ids) when it does this.

So what I'm trying to do is make it behave in a predictable way when I refresh the HTML of the original element (#myDialog). If I do this dynamically, sometimes the dialog doesn't open any more:

http://jsfiddle.net/t67y7/3/

Or sometimes the dialog opens with the old HTML (because it's cached at the bottom of the page that way). What is up with this?

like image 909
Milimetric Avatar asked Aug 17 '11 21:08

Milimetric


2 Answers

Since nobody seems to have any idea how to tame this beastly dialog, here's the best thing I've come up with to date. I'll accept any superior alternatives.

var original = $('#dialogId')[0];
var clone = $(original).clone().attr('id', 'dialogIdClone');
var saveHtml = $(original).html();
$(original).html('');
$(clone).dialog({
    ... // other options
    open: function (){
        // add any dynamic behavior you need to the dialog here
    },
    close: function(){
        $(clone).remove();
        $(original).html(saveHtml);
    }
});

The purpose of this whole craziness is to keep the HTML of the original dialog unique on the page. I'm not really sure why this can't be the built-in behavior of the dialog... Actually, I don't understand why jQuery UI needs to clone the HTML to begin with.

like image 54
Milimetric Avatar answered Jan 01 '23 14:01

Milimetric


I know this has been posted for a while, but a less extensive way to handle this issue would be:

$('#your-dialog').dialog({
    ... // other options
    open: function (){
        // add any dynamic behavior you need to the dialog here
    },
    close: function(){

    }
});
$('#your-dialog').remove();

This is due to dialog widget wants to be able to control the display and will wrap the inner content of the original dialog then create a brand new one at the bottom of the body.

The draw back of this solution is that the dialogs have to be the first to be initialized to ensure all your 3rd party library widget will operate properly.

like image 24
Kevin T. Avatar answered Jan 01 '23 13:01

Kevin T.