Nils
Nils

Reputation: 1996

jquery dialog - replacing dialog element

I have a document with a #page div, which contains a jQuery dialog div #dia and the JS to create it. Something like this:

<script>
var x;
</script>
<div id="page">
    <div id="dia">bla</div>
    <script>
    $(function () { x = $('#dia').dialog(); });
    </script>
</div>

This works fine so far. However, now I need to remove the contents of #page and replace them with new content. This new content will contain another div with id #dia and the same JS code to make that one into a dialog as well.

This does not seem to work. Instead, it seems like x is still the old dialog from before the replacement.

What I think happens is that jQuery moves the #dia div somewhere else when I create the dialog and thus when I replace the contents of #page the old dialog is still there. Then, when my $('#dia').dialog() code runs it is just applied to the old div, which is already a dialog.

I have tried running $('#page').empty(), x.dialog('destroy') and x.remove() before replacing the elements but none of this seems to help.

How do I do this properly?

Upvotes: 0

Views: 359

Answers (2)

Moby&#39;s Stunt Double
Moby&#39;s Stunt Double

Reputation: 2550

You need to re-run the selector via a callback after loading new content. Something like so:

$("div#page").load("/your/url/", function() {
    x = $('#dia').dialog();
});

Otherwise, the pointer will still be pointing back at the obsolete element.

Alternatively, you could go more generic and do something like this in order to reload the variable every time #page is replaced:

var x;
function initDialog(){
    x = $('#dia').dialog();
}
$(document).ready(function(){
    $("div#page").ajaxSuccess(initDialog);
});

Hope this helps.

Upvotes: 1

Bic
Bic

Reputation: 3134

Your script is set to only run on document ready.

$(function() { ... });

is a short hand for

$(document).ready(function () { ... });

Because you are dynamically loading the content into the page, but not actually changing the page, it will not fire a new document ready event. Subsequently, the value of x will not get changed, and the new content will not get converted to a dialog.

If you are going to dynamically load in the content, without reloading the page, you need to use a callback function to re-trigger the dialog initialize.

<script>
    var x;

    function reloadContent(url) {
        $("#page").load(url, function () {
           x = $("#dia").dialog();
        }
    }
</script>
<div id="page">
    <div id="dia">bla</div>
    <script>
        $(function () { x = $('#dia').dialog(); });
    </script>
</div>
<button type="button" onclick="reloadContent('new/url/for/content');>Change Content</button>

If you are going to manually swap out the content by using $.html(), then you will also have to manually reinitialize the dialog box as well.

Upvotes: 1

Related Questions