Introduction
So you are developing these great web applications that take advantage of jQuery and jQueryUI,
but there comes those times where you want to display a message box to the user. Suddenly, you are confronted with the fact that no matter how much work you
have put into styling your site, the JavaScript alert dialog boxes are to put it simply lame. You aren't alone (there should be a support group) and
that is where I was over a year ago.
In this article I will go over how you can stop using those old JavaScript alert dialogs and instead, use something that will fit with the themes you have
defined and can be used with your deployment of a jQuery UI themed application.
Background
OK, so it was a year ago that I published jQuery
UI Alerts Dialog using ThemeRollers. In fact, before I proceed, I will let
you go read that article so that you are all up to speed with what I will
discuss in this article.
Back?? OK, so you either read the article and loved it, or you are brave and saying screw the details, wanting instead to jump in head first. Personally, I am more
the brave type as well though my wife has a different title for it. While I was particularly proud of my achievement I would have never guessed the amount of
input I received on it here at CodeProject as well as in email and the various sites where I shared a link to
it.
All that input led to my head getting bigger than it already is, as well as leading me to creating the site jqalert.com. I
then began work on all the new features requested, bug fixes, and ideas I thought would make a great addition. It took me awhile but mostly because I was
off working on other projects.
Basics of using jqAlert
If it's not already obvious, one of the major dependencies for using this project is that you have to also include jQuery and jQueryUI. This is very
important to remember otherwise the dialogs won't work.
From the following code snippet you will notice that when the plugin is loaded it first checks for the existence of jQueryUI, without it you get nothing. I
have often debated popping one of those nasty browser alert dialogs, but decided against
it each time if only for my pure dislike of them.
(function($) {
if ($.ui) {
However you choose to load libraries is up to you. I used to take a purist stand of CSS and
JavaScript libraries being loaded in
the <head>
section of an HTML file and over the last year has moved away from it. I still load all the CSS
in the <head>
(like I had a choice otherwise) but I have started migrating all my
JavaScript loads to just before
closing the <body>
of the document.
The following is a snippet that I use regularly in my development of late:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script src="jquery.alerts.js"></script>
The exception to the above, of course, would include the events where you are running
JavaScript in the <head>
on startup that
might require jQuery or some other JavaScript framework. Though personally I believe this this is
a practice that should be avoided
at all costs.
Now you will want to make sure that you have a theme for jQueryUI loaded. You can either build your own or choose from one already
built. My preference is for the smoothness theme, but you should go check out all the themes or build
your own at the
jQuery UI ThemeRoller.
The nice thing with choosing one of the already built themes is that you can pull it down from a common CDN like
Google or Microsoft if you want.
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css" />
Details of Using jqAlert
So let's go over the parameters and properties that you will want to know while using jqAlert. Before we go over them though, it should be understood, that with
exception for the message
parameter everything else is optional. While you may omit the message
parameter, doing so will cause the
display of a dialog with the message of undefined to be displayed.
This may come in handy when using the alert to test or debug the validity of a variable.
jqAlert Parameters
- message
Message that will be displayed in the dialog to the user.
- options
An array of properties that affect the display and characteristics of the dialog being displayed.
jqAlert properties for dialog options
- title
Defines the title displayed on the dialogs title bar.
- icon
Defines the icon displayed with the message. Short-hand version of the jQuery glyphs (subtract ui-icon-).
- customIcon
Property that allows you to define a custom icon created in your CSS. The icon will have to be
URL encoded as a class in CSS to prevent flickering.
Also since the dialog is dynamically generated there is no guarantee that if you supply an <image> that it will be loaded as a server call
is required.
- show
The property that allows you to define the animation effect for how the dialog is displayed. Click here for
a list of effects.
- hide
The property that allows you to define the animation effect for how the dialog is closed. Click here for
a list of effects.
- timer
Define a timeout for how long the dialog will be displayed. Supplying a value of -1
will disable the timer.
- allowEscape
Property that allows you to set whether a dialog can be closed by hitting the escape key or not. The default is false
, meaning that the user
cannot close the dialog by pressing escape.
- buttons
From this property you can supply the array of buttons that will be displayed with the dialog being used. The exception of course being the inform
which does not support buttons.
jqAlert Buttons
With exception of inform
, all of the jqAlert dialogs come with a default set of buttons. However since you will most likely want to be notified
of which button was clicked this will most likely be a property that you are setting.
- title
The property that defines the text which will displayed on the buttons face.
- callback
A function property to be used as a callback for when the button is pressed.
- css
This property allows you to associate a custom css class to button.
jqAlert Notifications
To keep track of state for the dialogs you can also implement following notification functions to inform you of an event
occurring:
- onTimeout
In the event that a timer value was given this callback is used to notify that the timeout has been reached. A couple pieces of important information
is that the dialog is closed however the html
that was dynamically generated still remains.
- onClose
A callback notification that when supplied will notify when the dialog has been closed. Informs that the dialog has been closed and that furthermore the
dynamically generated HTML has been removed.
Using jqAlert (Example Code)
You will find most of these examples in the download that you can readily use. The following is a screenshot of the test screen you get from the download.
I haven't included sample code to exercise and display all the options available. Doing so would make this article much longer than it already is and would
take away the excitement of discovery from you.
Alerts
The alert dialog box supports all of the default properties and by default comes with an Ok button included. Aside from the default properties alert dialogs
also come packed with the following properties:
- exception
The property that defines the name or type of exception message.
- stack
The property that defines the stack for the associated exception message.
These are properties that I have kept around from my original development on jqAlert. At the time I wanted to use an
alert dialog for displaying exception and stack information received from a failed
AJAX call to a server function. The following example gives
a demonstration of what I was looking to achieve.
$.ajax({
type: 'POST',
url: 'url/someService.asmx',
data: '',
contentType: '',
dataType: '',
success: function(msg) {
error: function (request, status, error) {
var info = $.parseJSON(request.responseText);
$.alert(info.Message, {
title: 'Error',
icon: 'alert',
exception: info.ExceptionType,
stack: info.StackTrace
});
}
});
As discussed earlier you can execute any of the dialogs by only supplying the message
parameter. For instance the following piece code would
result in the alert dialog below to displayed.
$.alert($('#txtSimpleMessage').val());
Ok so now you see how easy it is to display something like an alert
dialog with jqAlert. All of the remaining examples will deal with detecting
and dealing with the users input as I am sure in most cases you will want to take some determined action. In most of the following examples I will display
the code and then an image of the resulting dialog.
Important note - The display of the dialog will change to that of the theme that you are using for jQuery UI. In the case of these
examples I am using the smoothness theme. There are many others or you can create your own by visiting jQuery UI ThemeRoller.
Confirmations
$.confirm($('#txtSimpleMessage').val(),{
buttons:[
{
title:'Yes',
callback: function() {
$('#clickResult').text('Yes');
$(this).dialog("close");
}
},
{
title:'No',
callback: function() {
$('#clickResult').text('No');
$(this).dialog("close");
}
},
{
title:'Cancel',
callback: function() {
$('#clickResult').text('Cancel');
$(this).dialog("close");
}
}
]
})
Results in the following:
Prompts
Prompt dialogs are just a bit different because with the response from the user comes the expectation of some kind of input from them. The following example
will demonstrate to you how to access result
entered by the user.
$.prompt($('#txtSimpleMessage').val(), {
buttons:[
{
title:'Ok',
callback: function() {
var result = $(this).find('#result').val();
$('#txtSimplePromptResult').val(result);
$('#clickResult').text('Ok');
$(this).dialog("close");
}
},
{
title:'Cancel',
callback: function() {
$('#clickResult').text('Cancel');
$(this).dialog("close");
}
}
]
})
Results in the following:
Information
For the inform dialog, since there are no buttons to interact with the user, you can either choose to assign the results of dialog to a var
that can
be used later to close the dialog. Associate a timer to close it after an elapsed amount of time, or allow the user to close it by hitting escape. If you
want you can use them together in some combined fashion as well.
The following is an example that I could use to display an information dialog while the user is waiting for the results of an
AJAX call to some
server side function:
var dlg = $.inform('call remote function');
$.ajax({
type: 'POST',
url: 'url/someService.asmx',
data: '',
contentType: '',
dataType: '',
success: function(msg) {
$(dlg).dialog("close");
},
error: function (request, status, error) {
$(dlg).dialog("close");
}
});
In the downloaded example you will find the inform dialog being used with a timer as well as allowing the user to hit the ESC key if they want
to close it. The following example comes from the downloaded source:
$.inform($('#txtSimpleMessage').val(), {
timer:5000,
allowEscape:true
});
Results in the following:
Conclusion
I hope that everyone gets as much as use from this as I have had in writing it. The idea grew from something simple and I have just extended it over time to
become what it is today. I have my own set of enhancements that over time will be added, the more important ones are those that will come from you.
Points of Interest
Check out jQuery and jQuery UI for some more great ideas about using either. I would also
recommend that you checkout the ThemeRoller when you get a chance.
Also go and take a look at Bootstrap. I have plans to continue extending jqAlert and even making a version
for use with Bootstrap.
Finally if you want to learn more or just track where or what things are happening with jqAlert go check us out here.
History
- December 16th, 2012: Initial version.
- Linked older article to this article.