Click here to Skip to main content
15,881,248 members
Articles / Web Development

jQuery UI Alerts Dialog using ThemeRollers

Rate me:
Please Sign up or sign in to vote.
4.67/5 (12 votes)
2 Mar 2013MIT7 min read 71.5K   1.3K   31   14
jQuery UI Alert dialogs to replace the JavaScript dialogs (alert, confirm, prompt)

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.

JavaScript
$.ajax({
    type: 'POST',
    url: 'url/someService.asmx',
    data: '',
    contentType: '',
    dataType: '',
    success: function(msg) { // do some stuff },
    error: function (request, status, error) {
        var info = $.parseJSON(request.responseText);

        // info should have all kinds of information in it, that I want to display
        // info.Message
        // info.ExceptionType
        // info.StackTrace
    }
});

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:

JavaScript
(function($) {
    if ($.ui) {
        // our code will go here
    }
})(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.

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

JavaScript
var defaultOptions = {
    title: 'Alert', // Information displayed in the title bar
    icon: 'alert',  // message type icon, just use the jquery ui icons
    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.

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

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

JavaScript
$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

JavaScript
$.alert('Message to be displayed to user.');

More Advanced Alert

JavaScript
$.alert('Message to be displayed to user', {
    title: 'Alert Title',
    icon: 'alert',
    buttons: { 'Ok': function() {
        // make sure we always add this line in our handlers
        $(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

JavaScript
$.confirm('Confirmation message to be displayed to user.');

Advanced Confirm

JavaScript
$.confirm('Confirmation message to be displayed to user.', {
    title: 'Confirmation Title',
    icon: 'help',
    buttons: {
        "Yes": function() {
            // make sure we always add this line in our handlers
            $(this).dialog("close");
        },
        "No": function() {
            // make sure we always add this line in our handlers
            $(this).dialog("close");
        },
        Cancel: function() {
            // make sure we always add this line in our handlers
            $(this).dialog("close");
        }
    } }
});

Prompt Dialogs

Simple Prompt

JavaScript
$.prompt('Question to be displayed to user.');

Advanced Prompt

JavaScript
$.prompt('Question to be displayed to user.', {
    title: 'Prompt Title',
    icon: 'help',
    defaultResult: 'Default response message',
    buttons: {
        "Ok": function() {
            // result value is stored in this.all.result.value

            // make sure we always add this line in our handlers
            $(this).dialog("close");
        },
        Cancel: function() {
            // make sure we always add this line in our handlers
            $(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:

JavaScript
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

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
United States United States
I am software developer with over 20 years of professional experience. I have been employed as a software developer since the early 90′s back when Microsoft’s Windows 3.1x was gaining popularity and IBM’s OS/2 was the predominant leader in 32-bit PC based Operating Systems.

Prior to choosing this as my profession I had studied architecture and then later Electrical and Mechanical engineering in college. As a young kid growing up I always played with computers, my first computer was a TRS-80 that I would spend countless hours writing programs for, I never really thought of programming as a profession. The story goes that in my final year of college I took a C/C++ programming class and had so much fun working on the various projects that my professor told me something that changed everything.

“You know they pay people to do stuff like this for a living?” – Professor Bolman

Check out my blog here.

My current and ever evolving projects:

jqAlert javascript alerts done right for those using jQueryUI.
DooScrib Doodle and scribble pad written in javascript for use with HTML5 Canvas.

Comments and Discussions

 
GeneralVote of 5 Pin
karenpayne22-Jun-15 11:26
karenpayne22-Jun-15 11:26 
Found your Github code first and found it easy to use the confirm.
Karen Payne
Programming is an art form that fights back

GeneralRe: Vote of 5 Pin
Dennis E White22-Jun-15 12:29
professionalDennis E White22-Jun-15 12:29 
QuestionAny chance of making this available under the MIT license? Pin
Member 956135131-Oct-12 5:15
Member 956135131-Oct-12 5:15 
AnswerRe: Any chance of making this available under the MIT license? Pin
Dennis E White31-Oct-12 8:28
professionalDennis E White31-Oct-12 8:28 
GeneralRe: Any chance of making this available under the MIT license? Pin
Member 956135131-Oct-12 8:39
Member 956135131-Oct-12 8:39 
QuestionRemove Icons Pin
Member 86890525-Mar-12 11:45
Member 86890525-Mar-12 11:45 
AnswerRe: Remove Icons Pin
Dennis E White5-Mar-12 19:44
professionalDennis E White5-Mar-12 19:44 
GeneralRe: Remove Icons Pin
Member 86890526-Mar-12 4:15
Member 86890526-Mar-12 4:15 
GeneralMy vote of 5 Pin
2LM6-Dec-11 19:11
2LM6-Dec-11 19:11 
QuestionSmall addition Pin
Hugo de Vreugd5-Dec-11 21:40
Hugo de Vreugd5-Dec-11 21:40 
AnswerRe: Small addition Pin
Dennis E White6-Dec-11 3:44
professionalDennis E White6-Dec-11 3:44 
QuestionScreenshots required Pin
sumit_4palz5-Dec-11 17:56
sumit_4palz5-Dec-11 17:56 
AnswerRe: Screenshots required Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)2-Mar-13 5:49
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)2-Mar-13 5:49 
GeneralRe: Screenshots required Pin
Dennis E White2-Mar-13 6:35
professionalDennis E White2-Mar-13 6:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.