Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Dialog - close after X seconds

This code works perfectly, except - dialog window will not close after X miliseconds as i expect...

setTimeout function is executed (i put alert() there and it worked...), so i assume problem is with $("#alert div").dialog('close'); but i do not know what is wrong...

if ($("#alert").length) {
    var title;
    if ($("#alert span").length) {
        title = $("#alert span").text();
    }
    $("#alert div").dialog({
        title: title,
        modal: true,
        open: function() {
            setTimeout(function() {
                $("#alert div").dialog('close');
            }, 2000);
        }
    });
}

EDIT: If it helps, here is HTML:

<div id="alert">
    <span>Password change</span>
    <div>Password was successfully changed.</div>
</div>

RESOLVED! Would be great if anyone has idea, why my code does not work...

like image 476
Martin Avatar asked Dec 15 '22 20:12

Martin


1 Answers

You have a scoping issue. Try this jsFiddle example:

if ($("#alert").length) {
    var title;
    if ($("#alert span").length) {
        title = $("#alert span").text();
    }
    $("#alert div").dialog({
        title: title,
        modal: true,
        open: function() {
            var foo = $(this);
            setTimeout(function() {
               foo.dialog('close');
            }, 2000);
        }
    });
}​

The reason this is happening, and not working like you might expect, is due to the way you reference the target div that becomes the dialog, and the way that jQuery UI builds the dialog. If you check out a developer console you'll see that jQuery pulls your div out of it's original position in the DOM and therefor no longer can be referenced to by #alert div since it's no longer a child of #alert. If you had given that div its own ID, it would work as expected and you wouldn't need the temporary variable to refer to it.

like image 100
j08691 Avatar answered Jan 11 '23 22:01

j08691