Introduction
With the use of jQuery and jQuery UI, I have all kinds of performance and visual improvements. So when it came down to dialog based alerts, I knew there was absolutely no way I was going to use the dinosaur based JavaScript alerts. I have seen several different options out there and it seemed like everyone had their own flavor:
I was even able to find a really great article here on Code Project that discussed a jQuery plugin that could be used for doing alert dialogs.
However, my needs were very specific and I really wanted it all done my way. So with all that in mind, I wanted something that took care of the following:
- Support for jQuery UI and ThemeRoller; I wanted to make sure that sites kept the same look and feel.
- Basic dialog alert that can be used in place of JavaScript
alert()
. - The alert will also need extended support to display error exceptions from an
$.ajax()
.
The third requirement was of particular importance for me because I wanted to be able to display exception information from an $.ajax()
request that resulted in an error.
$.ajax({
type: 'POST',
url: 'url/someService.asmx',
data: '',
contentType: '',
dataType: '',
success: function(msg) {
error: function (request, status, error) {
var info = $.parseJSON(request.responseText);
}
});
Background
I previously wrote an article on developing A jQuery plugin for an Adaptive 960 Grid System and some of the concepts covered in it will help in understanding the code behind creating the dialogs. In this article though the solution will be jQuery utility functions that do not come with the requirement of needing an HTML element to operate with.
The Basics
Let's take a look at the basic shell for the function container we will be working with:
(function($) {
if ($.ui) {
}
})(jQuery);
As before with the plugin, the initial layout is fairly simple. The first and last line are what will give our future functions access into jQuery. Since our utility functions are dependent on the presence of the jQuery UI, the if ($.ui)
is in place to make sure that it has been loaded.
Personal Habits in Development
In most of my development (99%), I use Visual Studio and I have learned that intellisense will do some of the work of letting me know that everything has been coded to load properly.
I also follow a disciple of loading libraries and such in the head
of the document and then code for that page I place at the bottom just before the closing tag of the body
. For the larger pages where a lot of document rendering will occur, I control the visibility of the body
in code so as to eliminate flickering in the document.
The Code
In those immortal words from one of my sons' favorite movies - So let's do this thing!
.
Alerts, Confirmations and Prompts
Back to the Basics
Let's go over what our dialog functions will receive and what they will need to operate.
$.alert = function(message, options)
Fairly simple and to the point.
We know that the basic requirement of any message dialog is that it displays a message to the user. Ok so that is solved by defining the first parameter received as the message
that will be displayed. We could stop there, but what about changing the title on the dialog, adding buttons and notifications for them, multiple types of messages, or those cool message type icons?
I am sure that you get my point, plus if you remember one of my original requirements was that I wanted support to display exception information from an $.ajax()
call.
Options, more control of what gets displayed
So instead of creating a function with different parameters, I decided to go with the idea of supplying an object for passing in options
that each of the functions could then work with. In keeping with the simple theme that a message dialog sometimes will only display a message, we will make options
an optional parameter.
To handle this, we will need to create a set of defaultOptions
for our functions to work with.
var defaultOptions = {
title: 'Alert',
icon: 'alert',
buttons: { "Ok": function() { $(this).dialog("close"); } }
};
Ok, so the basic default options will be:
title
: This is the string
that will be displayed in the title bar of the dialog.icon
: The message type icon; I chose to use jQuery UI icons and will be taking the part of the name that comes after ui-icon-
.buttons
: An array of button names and accompanying functions for each.
For the alert and prompt dialogs, I added the following default options:
exception
: A string
to be displayed which represents the exception received.stack
: A string
which represents the stack trace accompanying the exception information.defaultResult
: A string
representing a default value to be displayed when prompting for information.
With all the default options defined, we will add code for the event when a developer changes or overloads them.
if (options) {
defaultOptions = $.extend(defaultOptions, options);
}
In the event that we receive a set of options, we are going to use the jQuery $.extend()
function to update the defaultOptions
.
Building a Dialog
The required layout has already been defined for us by jQuery UI - Dialog so we just have to code around those requirements.
var $dialog = $('#confirmDialog');
$dialog.remove();
$dialog = $("<div id='confirmDialog' style='display:hidden' title='" +
defaultOptions.title + "'></div>").appendTo('body');
$('#confirmMessage').remove();
$("<p id='confirmMessage'><span class='ui-icon ui-icon-" +
defaultOptions.icon + "' style='float:left; margin:5px 10px 20px 0;'>
</span>" + message + "</p>").appendTo('#confirmDialog');
First shortcut the $('#confirmDialog')
since that is going to be worked with a couple of different times. Then, using the jQuery .remove()
function, remove any elements that might exist from previous calls.
Next, build the div
that will actually contain the dialog, setting its display to hidden and adding title information from our defaultOptions.title
, and then use the .appendTo()
to add this to the body
.
The final step then is to build the paragraph (p
) that will contact the defaultOptions.icon
message type icon as well as the message
that will be displayed to the user.
You will notice that $('#confirmMessage').remove();
was added, technically these elements should have been removed with the .remove()
call done for $dialog
, I added this code to just make things more readable.
Displaying the Dialog
So with everything built, the last step is to actually display it all to the user. Luckily for us, a lot of the work for displaying HTML information as a dialog has already been taken care of by the jQuery UI Dialog control.
$dialog.dialog({
resizable: false,
height: 'auto',
width: 'auto',
modal: true,
buttons: defaultOptions.buttons
});
resizable
- Like most message dialogs I have ever seen, the user cannot and does not need to resize them.height
and width
- Setting this to auto so that the Dialog will dynamically adjust the size of the dialog.modal
- We don't want the user interacting with other parts of page while our dialog is displayed.buttons
- This is the array of buttons and their callbacks that were originally supplied.
The only time that we will stray from the above is when working with $.alert()
dialogs that have exception and more importantly stack trace information. Since some stack traces can be long and contain a lot of information, I chose to cap the width
in these cases to a maximum of 960px.
Using the Code
So let's do a quick overview of how to use all this. If you haven't already downloaded the source, then now would be a great time. It comes with a sample page that offers a full demonstration of all the message dialogs and how to work with each of them.
Alert Dialogs
Simple Alert
$.alert('Message to be displayed to user.');
More Advanced Alert
$.alert('Message to be displayed to user', {
title: 'Alert Title',
icon: 'alert',
buttons: { 'Ok': function() {
$(this).dialog("close");
} }
});
Most everything here we have already covered, except the contents of the handler for when a buttons is pushed. Something that is required in all of them is code to actually close the dialog. Whether you want that code to be the first line executed or the last is totally up to how you are using the dialog. However, it is important to note that without that line of code, the dialog will never close.
Confirm Dialogs
Simple Confirm
$.confirm('Confirmation message to be displayed to user.');
Advanced Confirm
$.confirm('Confirmation message to be displayed to user.', {
title: 'Confirmation Title',
icon: 'help',
buttons: {
"Yes": function() {
$(this).dialog("close");
},
"No": function() {
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
} }
});
Prompt Dialogs
Simple Prompt
$.prompt('Question to be displayed to user.');
Advanced Prompt
$.prompt('Question to be displayed to user.', {
title: 'Prompt Title',
icon: 'help',
defaultResult: 'Default response message',
buttons: {
"Ok": function() {
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
Ok, so button handlers and message dialogs are great, but what about the ones where you were expecting input? That is, of course, important in the case of prompt dialog where the user will be entering in some value. In the return handler, you will access the this
object and buried inside of it all sorts of neat information.
You will find the result of what the user entered with the following piece of code:
this.all.result.value
Points of Interest
Check out the jQuery UI for the other features that it offers. Also take some time to view the ThemeRoller.
History
- 4th December, 2011: Initial version
- Check out the next article on this subject here.