hrz
hrz

Reputation: 313

Append jQuery UI dialog to its parent

I have the following html:

<ul id="sortable">
<li class="ui-state-default">1
    <div class="dialog-modal" title="Animal Facts" style="display:none;">
    <p>What is the fastest animal on Earth?</p>
    </div>
  </li>
<li class="ui-state-default">2
<div class="dialog-modal" title="Animal Facts" style="display:none;">
<p>What is the largest animal on Earth?</p>
</div></li>

​ and the following jQuery code:

$( ".dialog-modal" ).dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true
        });

$('.ui-state-default').click(function() {
    $(this).find("div").dialog( "open" );
 });

This does not open the modal dialog on click, what am I missing?

Thanks for the help.

Upvotes: 1

Views: 4954

Answers (1)

Irvin Dominin
Irvin Dominin

Reputation: 30993

This is a current behavior of the jQuery UI dialog.

When defined the jQuery UI dialog is created and appended to the body.

The workaround solution is to append the dialog to its original parent after the creation like:

$(function () {
    $(".dialog-modal").each(function (index) {

        var origContainer = $(this).parent();

        $(this).dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            create: function () {
                $(this).closest('div.ui-dialog')
                    .click(function (e) {
                    e.stopPropagation();
                });
            }
        }).parent().appendTo(origContainer);
    });

    $('.ui-state-default').click(function (event) {
        $(this).find("div").find(".dialog-modal").dialog("open");
    });
});

An important note: look at the create event defined; it's necessary because, the open dialog method executed on the .ui-state-default class elements click is triggered on every click inside the dialog! It's formally correct because now the dialog is contained inside its parent and the click is propagated to the parents with .ui-state-default class. With stopPropagation the problem is solved.

It's a bit hackish, but it works.

Working fiddle: http://jsfiddle.net/IrvinDominin/Avtg9/8/

With the future version of jQuery UI 1.10.0 will be added the option appendTo, to handle this situation without any workaround http://api.jqueryui.com/dialog/#option-appendTo

Upvotes: 2

Related Questions