Check out this simple dialog plugin:
http://jsfiddle.net/kVzJZ/
(function($) {
var dialogElement = '<div class="dialog-box"></div>';
$.openDialog = function(options) {
// Create the dialog DIV without adding it to the document
var dialog = $(dialogElement);
dialog.appendTo('body');
// Apply basic CSS to the dialog
dialog.css({
position: 'absolute',
'z-index': Math.pow(2,32)
});
// Position the dialog in the center of the screen
var horizontalOffset = ($(window).width() - options.width || dialog.outerWidth()) / 2;
var verticalOffset = ($(window).height() - options.height || dialog.outerHeight()) / 2;
dialog.css({
left: horizontalOffset,
right: horizontalOffset,
top: verticalOffset,
bottom: verticalOffset
});
// Return the dialog object for chaining
return dialog;
};
}(jQuery));
$.openDialog({width: 250, height: 150}).append('Greetings!');
You can enhance this plugin further by adding functionality like closing the dialog on pressing the Escape key or implementing a title bar with buttons. However, these tasks are likely familiar to you already.
Here are a couple of things to remember when developing dialogs:
- Ensure a sufficiently high z-index to keep the dialog at the forefront
- Insert the dialog element into the
BODY
Based on my experience, performance can be optimized by not always including the dialog HTML in the initial page load. While this contradicts graceful degradation principles, reducing the complexity of the DOM tree tends to improve app speed. Thus, it's advisable to add the dialog element dynamically when required.
UPDATE: It's important to note that my dialog plugin doesn't require pre-existing HTML on the page. It generates a new div, so you aren't selecting an element and transforming it into a dialog. Instead, a dialog is created from scratch.