Martin
Martin

Reputation: 1392

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...

Upvotes: 4

Views: 8121

Answers (2)

j08691
j08691

Reputation: 207901

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.

Upvotes: 12

Oscar Jara
Oscar Jara

Reputation: 14187

Tested and working live demo:

http://jsfiddle.net/oscarj24/q6tD9/2/

I think this way is better:

jQuery.fn.exists = function(){return this.length>0;}

$(function() {
    if($('#alert').exists()){
        var modal = $('#alert div');
        modal.dialog({ title: $('#alert span').text(), modal: true });
        var opened = modal.dialog('isOpen');
        if(opened){
            setTimeout(function(){ 
               modal.dialog('close'); 
            }, 2000);
        }
    }
});​

Upvotes: 0

Related Questions