Javascript offers two very useful input controls which block the user from all other interaction with a web-page (alert and confirm), however they are not particularly flexible, attractive or even meaningful at times. Therefore I introduce the Javascript class 'Alert' which provides customisable dialogue input controls. Current version: 1.2.

Introduction

Desktop application programmers have a considerable array of UI controls at their disposal that web-developers simply don't have access to through client-side scripting such as Javascript. One of these controls, which is common in its use across all platforms, is the dialogue box which is typically provided by the host operating system. Desktop application programs have considerable control over the dialogue boxes that they use, including button position, text and functions. Javascript on the other hand provides only alert() and confirm() which are not always ideal for use in a web based application.

To solve this problem I've developed a Javascript class called 'Alert' which provides a complete set of controls to allow developers to create custom dialogue boxes within a web-application. My intention was have a compact library, providing functions which can replace alert() and confirm(), with the ability to be expanded as the developer needs. Of course you should be careful with a new UI component which replaces a control that the end user is already use to. Therefore, I suggest that if you use Alert, then don't also use the standard Javascript functions, and use Alert only where appropriate.

Alert attempts to combine both the 'feel' of traditional Javascript alert message with the known interface paradigms (from the user's point of view) of a desktop application's dialogue box. This is done by first of all ensuring that all Alert dialogue boxes are 'blocking'. In the true sense of blocking Javascript doesn't provide any functions which allow for this behaviour (which is fair enough since Javascript engines are single threaded), however Alert replicates this behaviour by clever use of events on the page. Secondly, Alert appears like a desktop dialogue box because you don't need to use a mouse to operate it. Rather you can use the keyboard as you would expect (enter to confirm, left and right to select buttons).

Usage

Alert is a reasonably simple module to use, which can be included on your own site (for free!) and readily integrated with your code. To use Alert on your own web-pages the first thing to do in include the two Javascript files which are required (they could readily be combined into one) and a single CSS file:

  • JS Core (js-core.js) which is my micro library for providing event handling, page loading and logging functions. More on this in another reflection. You could replace the JS Base code used in Alert with YUI code - or whatever other library you wish to use.
  • Alert behaviour (alert.js) provides the alert class and all the functions we need in order to create custom dialogue boxes.
  • Alert styles (alert.css) provides all styling information needed for the dialogue box (all display information is set in this file, rather than in the Javascript - as it should be).






Alert will write in, on-the-fly, all of the DOM structure it needs in order to operate (this structure is documented in the alert.css file for styling), so you don't need to worry about including any extra HTML on your page. Similarly, the Alert Javascript object is self-initialising, so you can simply start using it.

Alert provides three basic functions for you to use:

  • Alert.fnAlert( string [, function])
  • Alert.fnConfirm( string [, function [, function]])
  • Alert.fnCustom( object )

Standard alert messages - Alert.fnAlert

To replace the standard alert() function, Alert provides Alert.fnAlert which takes either one or two arguments. The first is the string which will be used in the message for the dialogue box, and the second (which is optional) is a reference to a function which will be run when the confirm button is pressed. The following is an example of a simple confirm alert box:

// Alert example
Alert.fnAlert( "Congratulations - you are using Allan's Alert controls!" );

Click here to try this example.

Standard confirm messages - Alert.fnConfirm

Similar to fnAlert Alert provides Alert.fnConfirm to replace the standard Javascript confirm dialogue box. In this case the function takes up to three parameters, the first is the string to be displayed in the message, the second (which is optional) is the function to run when the 'Okay' button is selected, and the third (which is also optional) is the function to run when the 'Cancel' button is pressed. The following is a simple example of a confirm dialogue box, which will then use fnAlert to tell you which button you selected (of course you would do something a lot more sophisticated!):

// Call back functions
fnCallbackOkay = function () {
	Alert.fnAlert( "The okay button was selected." );
}

fnCallbackCancel = function () {
	Alert.fnAlert( "The cancel button was selected." );
}

// Confirm function
Alert.fnConfirm(
	"Would you like to continue to learn about the Alert controls?",
	fnCallbackOkay,
	fnCallbackCancel );

Click here to try this example.

Custom dialogues - Alert.fnCustom

In the example above we see one of the major draw backs of traditional Javascript confirm messages, replicated in an Alert dialogue box. The problem is that the answers simply don't make any sense with respect to the question: "Would you like to continue to learn about the Alert controls? Okay / Cancel" should really be "Would you like to continue to learn about the Alert controls? Yes please! / No thanks". This leads us to the true power of Alert: custom dialogue boxes. The previous two functions are really just wrapper functions to provide an easy means of access to common applications, but custom dialogue boxes are the exciting thing. So lets just dive straight into an example and then we'll go through it line by line. This example performs exactly the same function as the confirm example above, but it gives reasonable answers on the buttons:

// Basic custom Alert
Alert.fnCustom( {
	'sTitle': 'Confirmation required',
	'sMessage': 'Would you like to continue to learn about the Alert controls?',
	'sDisplay': 'aabc',
	'aoButtons': [
		{
			'sLabel': 'Yes please!',
			'fnSelect': fnCallbackYes,
			'sClass': 'selected',
			'cPosition': 'c'
		},
		{
			'sLabel': 'No thanks',
			'fnSelect': fnCallbackNo,
			'cPosition': 'b'
		}
	]
} );

Click here to try this example.

Line by line:

  • 2. Call the Alert.fnCustom function and pass it a Javascript object
  • 3. Set the title for the alert box
  • 4. Set the message for the alert box
  • 5. Define the display positions for the buttons (we'll come back to this)
  • 6. Define each button as an object in an array (aoButtons)
  • 8. The label for the 'Yes please' button
  • 9. Call back function for when the 'Yes please' button is selected - I'm using a slightly different call back function from the confirm example - again so it make sense following what you (the user) have selected.
  • 10. Class of the button. In Alert the class 'selected' means that this button is the default button
  • 11. Position of the button, based on the position of that character in sDisplay
  • 14-16. Definition of the 'No thanks' button following the same rules as the 'Yes please' button

This is just a simple example of what Alert can do. The number of controls it provides are much more extensive than this example shows, and in the following section I'll show a few more advance examples. For a complete list of the controls that Alert provides, please refer to the 'fnCustom' method in the API documentation.

Some of you may have wondered about the sDisplay and cPosition properties that I have in the example above. Some of you may even have recognised what I'm trying to do and where I got the idea from. In desktop applications the developer has a lot of control over the position and the size of a button in a dialogue box. This is not the case in the traditional Javascript alert and confirm functions, but Alert provides the opportunity to add this functionality in. Therefore I've created a 1 dimensional implementation of the CSS 3 advanced layout module.

The sDisplay property states the grid layout of a set of content elements. Each content element (in this case our buttons) can be positioned according to the letter we want to use. This is set using the 'cPosition' property of each button. CSS3.Info provides a great example and description of how the CSS 3 advanced layout module works.

As an example of how easy it is to defined button position and size in the grid using this method, below is another custom confirm box with a slightly different button layout:

// Basic custom Alert
Alert.fnCustom( {
	'sTitle': 'Confirmation required',
	'sMessage': "Isn't this button position control wonderful!?
I'm telling you - I can't wait for CSS 3 advanced layouts!", 'sDisplay': 'abbb', 'aoButtons': [ { 'sLabel': 'Me neither!', 'fnSelect': fnCallbackMeToo, 'sClass': 'selected', 'cPosition': 'b' }, { 'sLabel': "Pfft - when?", 'fnSelect': fnCallbackWhen, 'cPosition': 'a' } ] } );

Click here to try this example - guess where the emphasis lies...

You probably notice one little extra feature in the above example. I've included HTML in the message text. It's an HTML Alert box, so we can put any HTML we want into it, providing complete control and customisation in your alert boxes.

Examples

Previously I've provided functions which only scratch the surface of what you can do with Alert. In this section I'll provide three more in-depth examples of what applications it might be used for:

  • Text box input example
  • Styling example
  • Desktop application save dialogue example

Text box input example

The following example will open an Alert dialogue box and ask you for your name. When you click the 'Done' button it will then check to see if you have actually entered any information, and if not then it will change the title of the Alert box, prompting with a little more emphasis that you should enter your name. Once you've done so the function on the button when submitted will open another Alert box (just a normal alert this time) which will display your name with a thank you message.

I've used a couple of new properties in the object passed to fnCustom:

  • fnPreComplete - this is a function which will be run just after the user has selected a button. Probably typically used for input validation, as used here.
  • getElementById('alert_header') - in fnPreComplete I set the header text of the Alert box to be a bit more direct if there is no input and return false to cancel the completion of the submission of the button.
  • fnSelect - Not new but slightly different. I've used an anonymous function here rather than a reference
  • aoButtons - Again not new but slightly different. I've changed the order of the property declarations to highlight that since we are using objects here order is not important.
// User input example
Alert.fnCustom( {
	'sTitle': 'Enter you name please',
	'sMessage': '

With alert you can do all sorts of working things. \ Including asking for user input - please enter your name below:

\
\ \
', 'sDisplay': 'aaab', 'fnPreComplete': function() { if ( document.getElementById('ip1').value == '' ) { document.getElementById('alert_header').innerHTML = 'You need to enter you name please'; return false; } return true; }, 'aoButtons': [ { 'sLabel': 'Done', 'sClass': 'selected', 'cPosition': 'b', 'fnSelect': function() { var sName = document.getElementById('ip1').value; Alert.fnAlert( "Thank you "+sName+". Hopefully you can see how this could be expanded to do something a lot more clever" ); } } ] } );

Click here to try this example.

Styling example

Since the display of Alert is controlled by the included CSS file, we can make the visual appearance of Alert dialogue boxes different to suit each situation they are used in. In the following example two new properties are introduced. The first is sClass in the base object which gives the alert box a class of 'different' in this occasion, and the CSS therefore reflects this. The second change is that I've included the property bAnimate and set it to false which will cause the fade in and out of the Alert box not to happen. This gives a much snappier feel to an application, although perhaps not quite as smooth.

// Styling example
Alert.fnCustom( {
	'sTitle': 'Alert',
	'sMessage': "This alert box has a different style from all the others on this page",
	'sClass': 'different',
	'bAnimate': false,
	'sDisplay': 'abbc',
	'aoButtons': [
		{
			'sLabel': 'Funky',
			'sClass': 'selected',
			'cPosition': 'b'
		}
	]
} );

Click here to try this example.
Note that this example won't work perfectly in IE6 since I've used a positioned transparent PNG.

Desktop application save dialogue example

The following is an example with more buttons than the other demos on this page, simply to show how button declarations are made. I've given an example which might be expected to show up in a desktop application if you are shutting down the application and have unsaved work. You might be able to imagine using something like this on a web-based word processor for example.

// Save dialogue example
Alert.fnCustom( {
	'sTitle': 'Unsaved work',
	'sMessage': 'You have unsaved work - are you sure you wish to quit?',
	'sDisplay': 'abcd',
	'aoButtons': [
		{
			'sLabel': 'Cancel',
			'cPosition': 'a'
		},
		{
			'sLabel': "Don't save",
			'cPosition': 'c'
		},
		{
			'sLabel': 'Save all',
			'sClass': 'selected',
			'cPosition': 'd'
		}
	]
} );

Click here to try this example.

Change History

Version 1.2

  • New: Demo files are much cleaner.
  • Fixed: Much better support in IE - thanks to Nick Karasek.
  • Fixed: Mouse rollover and rollout functions weren't being called correctly.

Version 1.1

  • New: Support for IE6 and IE7.
  • Fixed: Using return key activated a selected link if the Alert was called from that link originally.

Version 1.0

  • First public release

Download & license

So there we have it, that is my Javascript Alert control set. In short, hopefully Alert provides web-developers with a tool which can be used for desktop like applications online, and will make desktop application developers somewhat jealous of us for a change for its ease of use and flexibility.

Alert is freely available, under a BSD style license which is available with the downloaded files. Please make use of the software as you wish, but I would be interested to know where and how it gets used, so please drop me a line if you do plan on using it. To get the software, simply download the ZIP file below and unzip it to your computer/server.

Enjoy!

Article image

API

The API functions shown in the tree below are the recommended methods of utilising Alert in your own applications. Private methods and properties are considered in the second tree.

  • object Alert
    Name space for alert methods and properties
    • method void:fnAlert( string [, string] )
      Typical alert box with an 'Okay' button
      • parameter string:sMessage
        Message to be shown
      • parameter function:sOkayText
        Function on click of button (default: null)
    • method void:fnConfirm( string [, function[, function]] )
      Typical alert box with an 'Okay' button
      • parameter string:sMessage
        Message to be shown
      • parameter function:sOkayText
        Function on click of button (default: null)
      • parameter function:fnCancel
        Function on click of button (default: null)
    • method void:fnCustom( object )
      Custom alert box - object properties:
      • [property string:sMessage]
        Message to be shown (default: '')
      • [property string:sTitle]
        Title of alert box (default: '')
      • [property string:sDisplay]
        Position definition for buttons (default: null)
      • [property string:sClass]
        Class of the alert box (default: '')
      • [property string:sBackgroundColor]
        Background colour (default: null)
      • [property float:fBackgroundOpacity]
        Background opacity (default: null)
      • [property int:iHeightPx]
        Height of the alert box, px (default: null)
      • [property int:iWidthPx]
        Width of the alert box, px (default: null)
      • [property function:fnPreDraw]
        Function to run just before display (default: null)
      • [property function:fnPreComplete]
        Function for before call back functions (default: null)
      • [property bool:bAnimate]
        Animate in and out the alert box (default: true)
      • [property array:aoButtons]
        Buttons array of objects with properties:
        • [property string:sLabel]
          Button label
        • [property char:cPosition]
          Position of button defined by sDisplay
        • [property string:sClass]
          Class of the button
        • [property int:iHeightPx]
          Height of button, px (priority over %)
        • [property int:iWidthPx]
          Width of button, px (priority over %)
        • [property int:iHeightPc]
          Height of button, %
        • [property int:iWidthPc]
          Width of button, %
        • [property function:fnSelect]
          Actions ifbutton is selected
        • [property function:fnRollOver]
          Actions if mouse is rolled over button
        • [property function:fnRollOut]
          Actions if mouse is rolled out of button

Private methods and properties

The following API tree shows Alert methods and properties which are used by Alert internally. I've included them here to complete the documentation of Alert, and it might be useful if you want to expand on what Alert currently does.

  • object Alert
    Name space for alert methods and properties (private)
    • method void:_fnCreateAlert (object )
      Same properties as fnCustom parameter
    • method void:_fnButtonSelected( event )
      • parameter event:e
        Document event object
    • method void:_fnCleanUp ( )
      Delete DOM objects and clean Alert namespace
    • method void:_fnAnimateIn ( )
      Animate in an alert box
    • method void:_fnAnimateOut ( )
      Animate out an alert box
    • method void:_fnSetOpacity ( node, float )
      • parameter node:nNode
        Target node
      • parameter float:fOpacity
        Opacity to set (0 to 1)
    • method float:_fnGetOpacity ( node )
      • parameter node:nNode
        Target node
    • method void:_fnKeyPress ( event )
      Deal with key presses
      • parameter event:e
        Document event object
    • method int:_fnGetButtonIndexFromPosition ( int )
      Get the index of a button from it's position
      • parameter int:iButtonNumber
        Button number that we want the index of
    • method int:_fnGetButtonPositionFromIndex ( int )
      Get the button number from it's position
      • parameter int:iButtonIndex
        Index we want the number of
    • method int:_fnGetCellIndex ( int )
      Get the index of a cell for a button
      • parameter int:iButton
        Index of cell with the target button
    • method int:_fnGetSelectedIndex ( )
      Get the index of the selected button
    • method void:_fnCreateMessage ( )
      Create message text in DOM
    • method void:_fnCreateButtons ( )
      Create the buttons in DOM + event handlers
    • method int:_fnCalculateNumberCells ( )
      Calculate from display how many cell to draw
    • method int:_fnCalculateCellWidth ( )
      Compute the width a cell should be based on its positioning
      • parameter int:iTargetButton
        Index of target button
    • method void:_fnCreateButtonsTable ( )
      Draw the buttons onto the alert box
    • method void:_fnCreateDomStructure ( )
      Add the required DOM elements