Learning jQuery: Optimize Using Modal Window or Dialog Box in JQuery UI

written by aext on December 18, 2009 in Javascript with 32 comments

This post is in the Learning jQuery series. Let’s enjoy a post today by learning how to maximize the Modal Windows or Dialog Box in jQuery UI. This post explains how to use this Dialog Box on the right way.

In the post that I published couple of months ago, I explained how to create a Modal window by using jQuery but not with the jQuery UI. That would be a lot of things to create your own without using any API. Today, with jQuery UI API, you can generate a same result but cool and easy-to-do.

A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the ‘x’ icon by default.

Implement jQuery UI API


Because this library depends on jQuery, before loading this jQuery UI library, you must load jQuery. This tutorial will load all the libraries from jqueryui.com or you can download the latest version of jQuery UI here. Add these code to your webpage:

  <!-- Begin all we need -->
  <link type="text/css"href="http://jqueryui.com/latest/themes/base/ui.all.css"rel="stylesheet" />
  <script type="text/javascript"src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
  <script type="text/javascript"src="http://jqueryui.com/latest/ui/ui.core.js"></script>
  <script type="text/javascript"src="http://jqueryui.com/latest/ui/ui.dialog.js"></script>
  <!-- End all we need -->

  <!-- Implement this one if you want to drag and drop the dialog box -->
  <script type="text/javascript"src="http://jqueryui.com/latest/ui/ui.draggable.js"></script>

  <!-- Implement this one if you want to resize the dialog box -->
  <script type="text/javascript"src="http://jqueryui.com/latest/ui/ui.resizable.js"></script>

[inline]

[script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"][/script]
[script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.draggable.js"][/script]

[script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.dialog.js"][/script]

[script type="text/javascript"]

$(document).ready(function() {

$(“div.demo a#button1″).click(function(e) {

e.preventDefault();
$(“#dialog1″).dialog();

});

});

[/script]

[/inline]

Basic Usage of Dialog jQuery UI


The basic usage will call the function dialog() which display a dialog message box contains the content of div element. However, because when the event start, jQuery did not initialize the divcontent, you only call this dialog one time unless you destroy the plugin instance first.

<!DOCTYPE html>
<html>
<head>
  ...
  <script type="text/javascript">
    $(document).ready(function() {

        $("a#button1").click(function(e) {

            e.preventDefault();
            $("#dialog1").dialog();

        });

    });
  </script>
</head>
<body>

<div id="dialog1"title="Click Me"style="display: none;">You have just clicked on Button 1</div>
<a id="button1"href="#">BUTTON 1</a>

</body>
</html>

Button 1

The problem is when you try to instantiate a new dialog every time the user performs some action events, the second call is ignored because the dialog has already been instantiated on that element. However, if you change your code with some differences likes this below, the dialog message box will display each time and every time.

Solution 1:
Remove the dialog functionality completely. This method will return the element back to its pre-init state, then call the dialog again.

  <script type="text/javascript">
    $(document).ready(function() {

        $("a#button2").click(function(e) {

            e.preventDefault();
            $('#dialog2').dialog('destroy');
            $("#dialog2").dialog();

        });

    });
  </script>

[inline]
[script type="text/javascript"]
$(document).ready(function() {

$(“a#button2″).click(function(e) {

e.preventDefault();
$(‘#dialog2′).dialog(‘destroy’);
$(“#dialog2″).dialog();

});

});
[/script]
[/inline]

Button 2

[smartads]

Solution 2:

Thanks to Scott González for this solution. According to his solution, the simple solution to this problem is to instantiate the dialog with autoOpen set to false and then call .dialog(‘open’) in the event handler.

[inline]
[script type="text/javascript"]
$(document).ready(function() {
var $dialog = $(‘

‘)
.html(‘This dialog will show every time!’)
.dialog({
autoOpen: false,
title: ‘Basic Dialog’
});

$(‘#button3′).click(function(e) {
e.preventDefault();
$dialog.dialog(‘open’);
});
});
[/script]
[/inline]

<script type="text/javascript">
$(document).ready(function() {
    var $dialog = $('<div></div>')
        .html('This dialog will show every time!')
        .dialog({
            autoOpen: false,
            title: 'Basic Dialog'
        });

    $('#button3').click(function(e) {
        e.preventDefault();
        $dialog.dialog('open');
    });
});
</script>

Use it on a right way


If you are using this jQuery UI Dialog for your website to notify users messages, the right way to use this dialog box for your whole website is write a function for this dialog and use it by calling your function. Your function would be like:

<script type="text/javascript">

function showDialog(str,strtitle)
{

    if(!strtitle) strtitle='Error message';

    $('#dialog').dialog('destroy');
    $('#dialog').show();
    $('#dialog').html(str);

    $("#dialog").dialog({
        resizable: false,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.9
        },
        title:strtitle
    });

}

</script>

And each time you want to display your dialog message box, you just need to change the title or dialog’s message.

    <div id="dialog"></div>
    <a onclick="showDialog('You are doing it in the right way', 'Message');"href="#">Button 4</span>

[inline]
[script type="text/javascript"]
function showDialog(str,strtitle)
{

if(!strtitle) strtitle=’Error message’;

$(‘#dialog’).dialog(‘destroy’);
$(‘#dialog’).show();
$(‘#dialog’).html(str);

$(“#dialog”).dialog({
resizable: false,
modal: true,
overlay: {
backgroundColor: ‘#000′,
opacity: 0.9
},
title:strtitle
});

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

$(“div.demo a”).click(function(e) {

e.preventDefault();

});

});

[/script]
[/inline]

class=”more”>Button 4

Confirmation Dialog Message Box


If you need users confirm before executing, the only way is display confirmation buttons (OK/Cancel) on the dialog. Each button has a callback function for when the button is clicked.

<script type="text/javascript">

function showDialog(str,strtitle)
{

    if(!strtitle) strtitle='Error message';

    $('#dialog').dialog('destroy');
    $('#dialog').show();
    $('#dialog').html(str);

    $("#dialog").dialog({
        resizable: false,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.9
        },
        title:strtitle,
        buttons: {
            'OK': function() {

                // Execute 
            },
            'Cancel': function() {

                // I'm sorry, I changed my mind                 
            }
        }
    });

}

</script>

[inline]
[script type="text/javascript"]

function showDialog2(str,strtitle)
{

if(!strtitle) strtitle=’Error message’;

$(‘#dialog’).dialog(‘destroy’);
$(‘#dialog’).show();
$(‘#dialog’).html(str);

$(“#dialog”).dialog({
resizable: false,
modal: true,
overlay: {
backgroundColor: ‘#000′,
opacity: 0.9
},
title:strtitle,
buttons: {
‘OK’: function() {
window.location.href = ‘http://www.dzone.com/links/learning_jquery_optimize_using_modal_window_or_di.html’;
},
‘Cancel’: function() {
$(this).dialog(“close”);
}
}
});

}

[/script]
[/inline]

class=”more”>Button 5

Conclusion


The jQuery UI API provides us advance effects that you can use to build highly interactive web applications. Like many jQuery UI effects, jQuery UI Dialog is easy to learn. Using it on the right way to help it be more flexible and scalability.