Click here to Skip to main content
Click here to Skip to main content

More jQuery UI Alerts Dialog Using ThemeRollers

, 2 Mar 2013 MIT
Rate this:
Please Sign up or sign in to vote.
A follow up article to jQuery UI Alerts dialog using ThemeRollers with new features added.

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) { // 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
        $.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.

//txtSimpleMessage has the value of the message to be 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() {
                // the users is stored in an input control with the id of result
                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) { 
        // close the the dialog
        $(dlg).dialog("close"); 

        // do some stuff 
    },
    error: function (request, status, error) {
        // close the the dialog
        $(dlg).dialog("close");
        
        // do some stuff 
    }
});

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,            // putting up a timer to close it automatically
    allowEscape:true    // allow the user to escape out of the inform dialog
});

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. 

License

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

Share

About the Author

Dennis E White
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.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionStyle PinmemberAlexander Shlinchak8-Jan-13 22:42 
AnswerRe: Style PinmemberDennis E White4-Mar-13 12:27 
GeneralMy vote of 1 Pinmembersangxiaojing27-Dec-12 22:20 
AnswerRe: My vote of 1 PinmemberDennis E White28-Dec-12 4:52 
GeneralRe: My vote of 1 PinmemberAdam Tibi5-Mar-13 3:27 
GeneralMy vote of 5 PinmemberSavalia Manoj M26-Dec-12 21:21 
QuestionCustomIcon PinmemberMember 969900819-Dec-12 6:55 
AnswerRe: CustomIcon PinmemberDennis E White19-Dec-12 8:36 
QuestionSourceCode PinmemberRuhollah Heidarpour18-Dec-12 19:52 
AnswerRe: SourceCode PinmemberDennis E White18-Dec-12 20:28 
AnswerRe: SourceCode PinmemberDennis E White18-Dec-12 20:38 
AnswerRe: SourceCode PinmemberDennis E White19-Dec-12 5:28 
GeneralMy vote of 5 PinmemberDennis E White18-Dec-12 18:01 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 2 Mar 2013
Article Copyright 2012 by Dennis E White
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid