The Dialog in jQuery User Interface 1.7

Exclusive offer: get 50% off this eBook here
jQuery UI 1.7: The User Interface Library for jQuery

jQuery UI 1.7: The User Interface Library for jQuery — Save 50%

Build highly interactive web applications with ready-to-use widgets from the jQuery User Interface library

$26.99    $13.50
by Dan Wellman | December 2009 | MySQL Open Source PHP Web Development

In this article by Dan Wellman, we will focus on the dialog widget. The dialog behaves in the same way as a standard browser alert, but it does so in a much less intrusive and more visitor-friendly manner. We look at how it can be configured and controlled to provide maximum benefit and appeal.

In this article, we will cover the following topics:

  • Creating a basic dialog
  • Work with dialog options
  • Modality
  • Enabling the built-in animations
  • Adding buttons to the dialog
  • IE6 and the selectbox z-index bug
  • Working with dialog callbacks

Traditionally, the way to display a brief message or ask a visitor a question would've been to use one of JavaScript's native dialog boxes (such as alert or confirm) or to open a new web page with a predefined size, styled to look like a dialog box.

Unfortunately, as I'm sure you're aware, neither of these methods is particularly flexible to us as developers, or particularly engaging for our visitors. For each problem they solve, several new problems are usually introduced.

The dialog widget lets us display a message, supplemental content (such as images or text), or even interactive content (like forms). It's also easy to add buttons, such as simple ok and cancel buttons to the dialog and define callback functions for them in order to react to their being clicked.

The following screenshot shows a dialog widget and the different elements that it is made of:

A basic dialog

A dialog has a lot of default behavior built-in, but few methods are needed to control it programmatically, making this an easy to use widget that is also highly configurable and powerful.

Generating the widget is simple and requires a minimal underlying markup structure. The following page contains the minimum markup that's required to implement the dialog widget:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="development-bundle/
themes/smoothness/ui.all.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery UI Dialog Example 1</title>
</head>
<body>
<div id="myDialog" title="This is the title!">Lorem ipsum dolor sit amet,
 consectetuer adipiscing elit.Aenean sollicitudin. Sed interdum pulvinar justo.
 Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper.
 Etiam tincidunt est vitae est.</div>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/jquery-1.3.2.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.core.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.dialog.js"></script>
<script type="text/javascript">

$(function(){

$("#myDialog").dialog();
});
</script>
</body>
</html>

Save this file as dialog1.html in the jqueryui project folder. To use the dialog, the following dependencies are required:

  • ui.all.css
  • jquery-1.3.2.js
  • ui.core.js
  • ui.dialog.js

The dialog widget is initialized in the same way as the other widgets we have already looked at—by calling the widget's plugin method. When you run this page in your browser, you should see the default dialog widget as shown in the screenshot at the start of this article.

As with the previous widgets we've covered, a variety of class names from the CSS framework are added to different elements within the widget to give them the appropriate styling for their respective elements, and any additional elements that are required are created on the fly. The following screenshot show these classes and the structure of the widget as interpreted by Firebug:

 

The dialog in the first example is fixed both in size and position, and will remain in the center of the viewport until it is closed. We can make the widget draggable, or resizable, or both easily. All we need to do is include the draggable and resizable component's source files with the other < script> resources at the end of the < body>.

 

It's not important that the draggable and resizable files are included in the page before the dialog's source file, they can come before or after and the widget will still inherit these behaviors. Any styling that is required, such as the resize indicator that appears in the bottom-left of the dialog, will be picked up automatically from the master CSS file.

 

Add the following two < script> elements directly before the closing < /body> tag in dialog1.html:

 

<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.draggable.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.resizable.js"></script>

 

Save this as dialog2.html and view it in a browser. The dialog should now be draggable and can be moved to any part of the viewport, but will not cause it to scroll if the widget is moved to an edge.

The dialog should also be resizable—by clicking and holding the resize indicator the widget can be made bigger or smaller. If the dialog is made bigger than the viewport then it will cause the window to scroll.

 

jQuery UI 1.7: The User Interface Library for jQuery Build highly interactive web applications with ready-to-use widgets from the jQuery User Interface library
Published: November 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Dialog options

 

An options object can be used in a dialog's widget method to configure various dialog options. Let's look at the available options:

Options

Default value

Usage

autoOpen

true

Shows the dialog as soon as the dialog() method is called when set to true.

bgiframe

false

Creates an <iframe> shim to prevent <select> elements showing through the dialog in IE6 (at present the bgiframe plugin is required). We'll look at this option in more detail shortly. This plugin is due to be retired in version 1.8 of the library and will be replaced by the new stackfix component.

buttons

{}

Supplies an object containing buttons to be used with the dialog. Each property name becomes the text on the <button> element, and the value of each property is a callback function, which is executed when the button is clicked.

closeOnEscape

true

If set to true, the dialog will close when the Esc key is pressed.

dialogClass

""

Sets additional class names on the dialog for theming purposes.

draggable

true

Makes the dialog draggable (use ui.draggable.js).

height

"auto"

Sets the starting height of the dialog.

hide

null

Sets an effect to be used when the dialog is closed.

maxHeight

false

Sets a maximum height for the dialog.

maxWidth

false

Sets a maximum width for the dialog.

minHeight

150

Sets a minimum height for the dialog.

minWidth

150

Sets a minimum width for the dialog.

modal

false

Enables modality while the dialog is open.

position

"center"

Sets the starting position of the dialog in the viewport. Can accept a string, or an array of strings, or an array containing exact coordinates of the dialog offset from the top and left of the viewport.

resizable

true

Makes the dialog resizable (also requires ui.resizable.js).

show

null

Sets an effect to be used when the dialog is opened.

stack

true

Causes the focused dialog to move to the front when several dialogs are open.

title

false

Alternative to specifying the title attribute on the widget's underlying container element.

width

300

Sets the starting width of the dialog.

zIndex

1000

Sets the starting CSS z-index of the widget. When using multiple dialogs and the stack option is set to true the z-index will change as each dialog is moved to the front of the stack.

 

 

As you can see, we have a wide range of configurable options to work with when implementing the dialog. Many of these options are Boolean, or numerical, or string-based, making them easy to set and work with.

 

Showing the dialog

In our examples so far, the dialog has opened as soon as the page has loaded, or when the dialog widget method is called, which is as soon as the page is ready in this case.

We can change this so that the dialog is opened when something else occurs, like a button being clicked, by setting the autoOpen option to false. Change the final < script> element at the bottom of dialog2.html to the following:

<script type="text/javascript">
$(function(){
var dialogOpts = {
autoOpen: false
};
$("#myDialog").dialog(dialogOpts);
});
</script>

Save this as dialog3.html. The widget is still created; the underlying markup is removed from the page, transformed into the widget, and then reappended to the end of the < body>. It will remain hidden until the open method is called on it. We'll come back to this option when we look at the open method a little later on.

Positioning the dialog

The position option controls where the dialog is rendered in the viewport when it is opened and accepts either a string or an array value. The strings may be one of the following values:

  • bottom
  • center
  • left
  • right
  • top

We can also supply different sensible combinations of these strings in an array, there's no point supplying an array containing the strings top and bottom. However, we can supply right and top for the widget to be positioned in the top-right of the viewport.

An array can also be used when you want to specify the exact coordinates, relative to the top-left corner of the viewport where the dialog should appear. Change the configuration object used in dialog3.html so that it appears as follows:

var dialogOpts = {
position: ["left", "bottom"]
};

Save this as dialog4.html. When using a string-based array we need to supply the values in a specific order—the value of the widget's position on the horizontal axis should be specified first, followed by its position on the vertical axis.

The following screenshot shows where the dialog can be positioned on the page using either a string or a string-based array:

When using integers in the position array we can specify any location on the page in which to position the dialog. Change the configuration object in dialog4.html to the following:

var dialogOpts = {
position: [100, 100]
};

Save this version as dialog5.html. This time, the dialog should appear exactly 100 pixels from the top and 100 pixels from the left edges of the viewport. Note that the axis order is the same as when using string values—horizontal followed by vertical. If the dialog is outside the maximum width or height of the viewport then the page will be scrolled.

The title of the dialog

The options table shows a title option. Although the title of the dialog (the actual text in the header of the widget) can be set using the title attribute of the underlying HTML container element, using the title configuration option gives us more control over how the title (the text) is displayed on the widget.

By default, the title text (in the header) of the dialog will not be selectable and will also not be displayed in the OSs default tooltip style. When using the title attribute on the underlying element, the text will appear within a < span> element, which is inside a < div> with the class name ui-dialog-titlebar. These elements will appear in the header of the widget.

If we want to inject additional elements into the DOM structure of the dialog (for additional styling perhaps or different behavior), we could do it using the title option. Change the configuration object in dialog5.html to the following:

var dialogOpts = {
title: '<a href="#">A link title!</a>'
};

Save this file as dialog6.html. The change in the widget should be apparent immediately, the span element in the widget header will now contain our newlink element. The following screenshot shows our new title:

Modality

One of the dialog's greatest assets is modality. This feature creates an overlay when the widget that sits above the page content but below the dialog is opened. The overlay is removed as soon as the dialog is closed. None of the underlying page content can be interacted with in any way while the dialog is open.

The benefit of this feature is that it ensures the dialog is closed before the underlying page becomes interactive again, and gives a clear visual indicator to the visitor that the dialog must be interacted with before they can proceed.

Change the configuration object in dialog6.html to this:

var dialogOpts = {
modal: true
};

This file can be saved as dialog7.html. Only a single property is required when adding modality and that is the modal option. When you view the page in a browser, you'll see the modal effect immediately.

The repeated background image that is used to create the overlay is styled completely by the CSS framework and is therefore fully themeable via ThemeRoller. We can also use our own image if we need to. The class name ui-widget-overlay is added to the overlay, so this is the selector to override if customization is required.

The following screenshot shows the modal effect (I've added some fake content to the page so that the effect of the modal can be fully appreciated):

Adding buttons

The button option accepts an object literal that is used to specify the different < button> elements that should be present on the dialog. Each property:value pair represents a single button. Let's add a couple of < button> elements to our dialog. Alter the final < script> element in dialog7.html so that it appears as follows:

<script type="text/javascript">
$(function(){
var execute = function() {
}
var cancel = function() {
}
var dialogOpts = {
buttons: {
"Ok": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
</script>

Save the file as dialog8.html. The key for each property in the buttons object is the text that will form the < button> label, and the value is the name of the callback function to execute when the button is clicked.

Each callback function is defined before the configuration object. If this is not done an error will be thrown by the widget when the button is clicked. In this example the functions don't do anything, we'll come back to this example shortly and populate these functions.

The widget will add our new buttons to their own container at the foot of the dialog, and if the dialog is resized then this container will retain its original dimensions. The < button> elements are fully themeable and will be styled according to the theme in use. The following screenshot shows how our new < button> elements would appear:

jQuery UI 1.7: The User Interface Library for jQuery Build highly interactive web applications with ready-to-use widgets from the jQuery User Interface library
Published: November 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Enabling dialog animations

The dialog provides us with a built-in effect that can be applied to the opening or closing (or both) phases of the widget. There is only a single effect that we can use, which is an implementation of the scale effect. Change the final < script> element in dialog8.html to this:

<script type="text/javascript">
$(function(){
var dialogOpts = {
show: true,
hide: true
};
$("#myDialog").dialog(dialogOpts);
});
</script>

Save this as dialog9.html. We set both the hide and show options to the Boolean value true; this enables the built-in effect, which gradually reduces the dialog's size and opacity until it gracefully disappears. The following screenshot shows an effect in motion:

Fixing IE6

I need not say much more than IE6 is anathema to web developers, and at the time of writing is unfortunately still with us. A major problem with this browser (sometimes referred to as the select box z-index bug), is the fact that < select> elements appear above any other content on the page. This can cause issues with widgets like the dialog that are supposed to float above any other page content. The following screenshot shows this bug in action:

Fortunately, the jQuery UI dialog comes with built-in protection in the form of the bgiframe option that fixes the selectbox issue by inserting an < iframe> element into the dialog, which blocks out any underlying < select> elements. In dialog9.html add a new < select> element to the page, and then change the configuration object so that it is like this:

var dialogOpts = {
bgiframe: true
};

Don't forget to link to the bgiframe plugin that can be found in the external directory, with the other < script> resources at the end of the < body>:

<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/external/bgiframe/jquery.bgiframe.js"></script>

Save the changed file as dialog10.html. Now in IE6, the widget will float above the select box as it should:

The < iframe> element will only be added in IE6, no other browsers will need it. It will receive all the attributes that it requires automatically, no further configuration or styling is required.

Configuring the dialog's dimensions

There are several options related to the dialog's size, and the minimum and maximum size that it can be resized to. We can add all of these options to the next example as they're all related, to save looking at them individually. Remove the < select> box and the link to the bgiframe plugin, and change the configuration object in dialog10.html to the following:

var dialogOpts = {
width: 300,
height: 300,
minWidth: 150,
minHeight: 150,
maxWidth: 450,
maxHeight: 450
};

Save this file as dialog11.html. The effect these options have on the widget is simple; the width and height options define how big the dialog is when it is first opened while the min- and max- options define how small or large the dialog can be resized to respectively. Care should be taken that the minimum width and height of the dialog do not cause the title to overflow or it may end up looking something like this:

As an additional note, assistive technologies and keyboard users may find the content difficult to navigate if the dialog is made too small. There is a usability tenant that insists dialog boxes should always be non-resizable, whereas windows should always be resizable.

While I don't think this a black-and-white rule, it may be wise to keep small, informational, text-based dialogs at a fixed size, while allowing dialogs richer in content, composed of both images and text to be resizable.

Stacking

The dialog is made so that it appears above any of the existing page content, and even provides the zIndex option in case we need to raise it slightly to cover our existing content. But what if we have two dialogs on the page? Do we need to separately define the zIndex for each dialog? How is focus taken into consideration?

Let's see if we can answer these questions by looking at another example, change the < body> of dialog11.html so that it has two dialog boxes on it:

<div id="dialog1" title="Dialog 1">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Aenean sollicitudin.
 Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis
 quis diam laoreet ullamcorper. Etiam tincidunt est vitae est.
</div>
<div id="dialog2" title="Dialog 2">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin.
 Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis
 quis diam laoreet ullamcorper.Etiam tincidunt est vitae est.
</div>

Now change the final < script> element so that it appears like this:

<script type="text/javascript">
$(function(){
$("#dialog1").dialog();
$("#dialog2").dialog();
});
</script>

Save this file as dialog12.html. We've added another dialog to the page, which is basically just a clone of the original with a different id attribute. In the < script> we simply call the widget method of both our underlying elements, we don't need a configuration object.

Because the widget method is called on the second dialog last, this dialog will automatically have a higher zIndex, so we don't need to worry about configuring this separately. It doesn't matter the order in which the dialogs appear in the underlying markup, it's the order of the widget methods that dictate each dialog's zIndex.

Because neither dialog has its position explicitly set, only the second dialog will be visible when our example page loads. However, both are draggable and we can align them so that they overlap slightly by dragging the second dialog away. If we click on the first dialog box its zIndex will automatically be increased to one higher than the second dialog box.

The stack option is set to true by default, so all of this behavior is automatically available with no additional configuration from us. If for some reason this behavior is not desired then we can disable it by supplying false as the value of the stack option.

Dialog's event model

The dialog widget gives us a wide range of callback options that we can use to execute arbitrary code at different points in any dialog interaction. The following table lists the option available to us:

Option

Fired when

beforeclose

The dialog is about to be closed.

close

The dialog is closed.

drag

The dialog is being dragged.

dragStart

The dialog starts being dragged.

dragStop

The dialog stops being dragged.

focus

The dialog receives focus.

open

The dialog is opened.

resize

The dialog is being resized.

resizeStart

The dialog starts to be resized.

resizeStop

The dialog stops being resized.

Some of these callbacks are only available in certain situations, such as the drag and resize callbacks, which will only be available when the draggable and resizable components are included. We won't be looking at these callback options in this article.

Other callbacks such as the beforeClose, open, close, and focus callbacks will be available in any implementation. Let's look at an example in which we make use of some of these callback options. In a new page in your text editor, add the following code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="development-bundle/themes/smoothness/ui.all.css">
<link rel="stylesheet" type="text/css" href="css/dialogTheme.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>jQuery UI Dialog Example 13</title>
</head>
<body>
<div id="status" class="ui-widget">
<div class="ui-widget-header">Dialog Status</div>
<div class="ui-widget-content"></div>
</div>
<div id="myDialog" title="This is the title">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
 Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpat ligula.
Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est.</div>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/jquery-1.3.2.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.core.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.dialog.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.draggable.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.resizable.js"></script>
<script type="text/javascript">
$(function(){
var dialogOpts = {
open: function() {
$("#status").find(".ui-widget-content").text("The dialog is open");
},
close: function() {
$("#status").find(".ui-widget-content").text("The dialog is closed");
},
beforeclose: function() {
if (parseInt($(".ui-dialog").css("width")) == 300 || parseInt($(".ui-dialog").css("height")) == 300) {
return false
}
}
};
$("#myDialog").dialog(dialogOpts);
});
</script>
</body>
</html>

Save this as dialog13.html. The page contains a new status box which will be used to report whether the dialog is open or closed. We've given the elements that make up the status box several CSS framework classes to make it fit with the theme in use and to cut down on the amount of styling we need to worry about.

Our configuration object uses the open, close, and beforeclose options to specify simple callback functions. The open and close callbacks simply set the text of the status box accordingly. The beforeclose callback that is fired after the close button on the dialog has been clicked but before it is actually closed, is used to determine whether or not to close the dialog.

We use a simple if statement to check the width and height of the dialog; if the dialog has not been resized we return false from the callback and the dialog remains open. This kind of behavior is of course a big no in terms of usability, but it does serve to highlight how we can use the beforeclose callback to prevent the dialog being closed.

We also use a custom stylesheet for this example. It's simple and contains the following rules:

#status { width:200px; }
#status .ui-widget-header {
font-family:Georgia; padding:5px;
}
#status .ui-widget-content { font-size:12px; padding:5px; }

Save this as dialogTheme.css in the css folder. When the page loads and the dialog is opened (as it is by default), the open callback will be executed and the status box should display a message as shown in the following screenshot:

One thing I should make clear is that the dialog widget only passes a single object (the original event object) to the callback functions. It does not pass the second ui object in version 1.7 (the current version at the time of writing). The second object will be introduced in version 1.8 of the library.

In this article, we have covered the following topics:

  • Creating a basic dialog
  • Work with dialog options
  • Modality
  • Enabling the built-in animations
  • Adding buttons to the dialog
  • IE6 and the selectbox z-index bug
  • Working with dialog callbacks

>> Continue Reading Extending The Dialog in jQuery User Interface 1.7.

 

About the Author :


Dan Wellman

Dan Wellman is an author and frontend engineer living on the South Coast of the UK and working in London. By day he works for Skype and has a blast writing application-grade JavaScript. By night he writes books and tutorials focused mainly on frontend web development. He is also a staff writer for the Tuts+ arm of the Envato network, and occasionally writes for .Net magazine. He's the proud father of four amazing children, and the grateful husband of a wonderful wife.

Books From Packt

jQuery 1.3 with PHP
jQuery 1.3 with PHP

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Learning jQuery 1.3
Learning jQuery 1.3

PHP Team Development
PHP Team Development

ICEfaces 1.8: Next Generation Enterprise Web Development
ICEfaces 1.8: Next Generation Enterprise Web Development

Symfony 1.3 Web Application Development
Symfony 1.3 Web Application Development

JBoss AS 5 Development
JBoss AS 5 Development

JBoss RichFaces 3.3
JBoss RichFaces 3.3

Your rating: None Average: 5 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
w
Y
U
U
w
2
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software