Thinking in programming

Things I like to talk about programming

Archive for the ‘GUI’ Category

betterSelects – Much better HTML select-elements

with 4 comments

Introduction: betterSelects is intended to “transform” the old-fashioned HTML select-elements in much more sophisticated and flexible controls (see a demo here and screen-shots below). The plugin is released under the Apache License version 2.

For me, there are some essential premises at the moment of writing an UI-Control:

  • Must offers important advantages over already existing related controls
  • Usability
  • Flexibility to customize
  • Performance
  • And for JavaScript controls, them must degrades successfully

Background: a normal HTML select element is too much rigid regarding the customization of its look and feel, as it does not support the coolest CSS effects (aka rounded corners, transparency, shadows, columns, animations, etc.). Thus, this plug-in was created to provide such features.

Currently supported features:

  • displaying items in columns
  • transparency
  • rounded corners
  • animations
  • shadows
  • customization of the expansion button
  • degrades successfully when JavaScript is not enabled
  • and in general, a full customization through CSS

Planned features for future versions:

  • navigation by using arrows keys
  • support for select-multiple
  • auto completion (useful?)
  • among other minor improvements

The usage is very straightforward; just include the provided CSS file and the JavaScript file, then:

$('select').betterSelects({
  zIndexMax: 99, // The first betterSelect control will use this value, it will be smaller for following controls
  expandTime: 100, // The time it takes to expand the options
  marginTop: 1, // Margin between the preview and the expanded options list
  itemsPerCol: 6 // Number of items per column. Use 0 for a single column
});

See the plugin in action here: http://betterselects.appspot.com/

The source is located on Google Code: http://code.google.com/p/betterselects/

A read-only copy of the code can be obtained from http://betterselects.googlecode.com/svn/trunk/

And at last but not at least, it would be great if you wish to do any kind of collaboration with this project, suggestions, corrections, comments, are very welcome. You can ask for commit access if you wish, of course!.

Screen-shots v0.5:

This slideshow requires JavaScript.

JavaScript sourcode v0.5:

/**
 * jQuery.betterSelects plugin v0.5
 * Date: 2010.10.09
 * Web: https://rogerpadilla.wordpress.com/betterSelects
 * Copyright 2010, Roger Padilla Camacho - rogerjose81@gmail.com
 * Licensed under the Apache License version 2
 */

/**
 * This plug-in is intended to "transform" the old-fashioned HTML select-elements in much more sophisticated
 * and flexible controls.
 * 
 * Background: a normal HTML select element is too much rigid regarding the customization of its look and feel,
 * as it does not support the coolest CSS effects (aka rounded corners, transparency, shadows, columns,
 * animations, etc.). Thus, to count with such features in that control is the purpose of this plug-in.
 * 
 * Currently supported features: displaying items in columns, transparency, rounded corners, animations,
 * shadows, customization of the expansion button, and in general, a full customization through CSS.
 * The plug-in degrades successfully when JavaScript is not enabled.
 
 * Planned features for future versions: navigation by using arrows keys, support for select-multiple,
 * auto completion (useful?), among other minor improvements.
 * 
 * The usage is very straightforward; just include the provided CSS file and the JavaScript file, then:
 * <code>$('select').betterSelects();</code>
 */
(function($) {

	/**
	 * Main function; used to initialize the plugin
	 */
	$.fn.betterSelects = function() {

		if(this.length >= 0) {
			// keep a reference of the jQuery object to access it on other functions
			$.fn.betterSelects.self = this;
			// Creates a 'betterSelect' control for each 'select' element in the matched set using the given configuration
			$.fn.betterSelects.opts = $.extend({}, $.fn.betterSelects.defaults, arguments[0]);
			$.fn.betterSelects.createBetterSelects();
		}

		return this;
	};
	
	
	/**
	 * Default configuration
	 */
	$.fn.betterSelects.defaults = {
		zIndexMax: 99, // The first betterSelect control will use this value, it will be smaller for following controls
		expandTime: 100, // The time it takes to expand the options
		marginTop: 1, // Margin between the preview and the expanded options list
		itemsPerCol: 6 // Number of items per column. Use 0 for a single column
	};


	/**
	 * Creates a 'betterSelect' control for each HTML select-element in the matched set using the given configuration
	 */
	$.fn.betterSelects.createBetterSelects = function(){

		var selectsData = [];
		var bsHTML, bs, bsExpandedHeight, pos, ul, itMinHeight, ele;

		/** Loop through the matched set of HTML select-elements to build a 'betterSelect' control emulating each 'select' in the set **/
		$.fn.betterSelects.self.each(function(){
			
			// TODO remove this when support for select-multiple get added
			if(!this.multiple){

				ele = $(this);
	
				// Hide the original HTML select-element
				this.className += 'accesible-hidden-element';
	
				// the select's index being processed
				pos = selectsData.length;
	
				// Build the HTML for the 'betterSelect' control'
				bsHTML = createBetterSelectHTML(this, pos);
	
				// Inserts the 'betterSelect' control in the DOM
				bs = this.parentNode.insertBefore(bsHTML, this.nextSibling);
				bs = $(bs);
	
				bs.children('.betterSelect-preview').css({minWidth: ele.width()});
				
				// Obtains the height of the betterSelect's options on expanded state
				ul = bs.children('.betterSelect');
				bsExpandedHeight = ul.height();
				// Collapse the betterSelect by default
				ul[0].style.height = 0;
				ul[0].style.zIndex = $.fn.betterSelects.opts.zIndexMax - pos;
				itMinHeight = bs.height();
				// Store data related to the original 'select' DOM-element to reference it later
				selectsData.push({height: bsExpandedHeight, itMinHeight: itMinHeight});
				ul.addClass('betterSelect-processed');
			}
		});


		/**
		 * Obtains the data source from the given HTML select-element
		 * @param srcElem Source select-element
		 * @return Extracted select's data
		 */
		function getSelectData(srcElem){

			var bsData = [];
			var selectedIndex = 0;

			for(var i=0, l=srcElem.options.length; i<l; i++) {
				if(srcElem.options[i].selected) {
					selectedIndex = i;
				}
				bsData.push(srcElem.options[i].innerHTML);
			}

			return {options: bsData, selectedIndex: selectedIndex};
		}


		/**
		 * Build the HTML displaying the options
		 * @param src Data source
		 * @param pos The index of the data source being processed
		 * @return Options's data
		 */
		function createBetterSelectOptionsHTML(src, pos) {

			var optionsHTML = '<div class="betterSelect-nc">';
			var classes = '';

			// if the data source is a HTML select-element
			if(src.nodeType) {
				src = getSelectData(src);
			}

			for(var i=0, l=src.options.length; i<l; i++){
				classes = 'betterSelect-it betterSelect-it-i-' + i;
				// marks the selected option
				if(i == src.selectedIndex) {
					classes += ' betterSelect-it-state-selected';
				}
				// close the previous colum and open a new one
				if(i > 0 && (i % $.fn.betterSelects.opts.itemsPerCol) === 0){
					optionsHTML += '</div>\
									<div class="betterSelect-nc">';
				}
				// adds an option to the list of options
				optionsHTML +=
					'<li id="betterSelect_it:' + pos + '.' + i + '" class="' + classes + '">\
						<span class="betterSelect-it-val"></span><span class="betterSelect-it-label">' + src.options[i] + '</span>\
					</li>';
			}

			optionsHTML += '</div>';

			return {options: optionsHTML, selectedIndex: src.selectedIndex, selected: src.options[src.selectedIndex]};
		}


		/**
		 * Build the betterSelect's HTML using the given datasource
		 * @param src Datasource
		 * @param pos The index of the datasource being processed
		 * @return betterSelect's HTML
		 */
		function createBetterSelectHTML(src, pos){

			var bsData = createBetterSelectOptionsHTML(src, pos);

			bsHTML = document.createElement('div');
			bsHTML.id = 'betterSelect_box:' + pos;
			bsHTML.className = 'betterSelect-box';
			bsHTML.innerHTML = '\
				<span id="betterSelect_preview:' + pos + '" class="betterSelect-preview">' + bsData.selected + '</span>\
				<span id="betterSelect_maximize:' + pos +'" class="betterSelect-maximize"></span>\
				<ul id="betterSelect:' + pos +'" class="betterSelect">' + bsData.options + '</ul>\
			';

			return bsHTML;
		}


		/**
		 * Expands/collapses the 'betterSelect' control in the given index
		 * @param pos Index of the 'betterSelect' control
		 */
		function changeSelectMaximizeState(pos){
			var ul = $('#betterSelect\\:' + pos);
			ul.stop();
			if(ul.is('.betterSelect-state-expanded')){
				minimizeSelect(pos, ul);
			} else {
				maximizeSelect(pos, ul);
			}
		}


		/**
		 * Expands the 'betterSelect' control specified by the given index
		 * @param pos Index of the 'betterSelect' control
		 * @param ul Options of the 'betterSelect' control
		 */
		function maximizeSelect(pos, ul){
			$('#betterSelect_maximize\\:' + pos).addClass('betterSelect-maximize-state-expanded');
			var bs = $(ul[0].parentNode);
			var bsOffset = bs.offset();
			bsOffset.top += selectsData[pos].itMinHeight + $.fn.betterSelects.opts.marginTop;
			ul.css({top: bsOffset.top, left: bsOffset.left});
			ul.addClass('betterSelect-state-expanded');				
			ul.animate({height: selectsData[pos].height}, $.fn.betterSelects.opts.expandTime, function(){
				// TODO move the following line to single-selects handlers
				ul.find('.betterSelect-it-state-selected').addClass('betterSelect-it-hover');
				ul.focus();
			});
		}


		/**
		 * Collapses the 'betterSelect' control specified by the given index
		 * @param pos Index of the 'betterSelect' control
		 * @param ul Options container of the 'betterSelect' control
		 */
		function minimizeSelect(pos, ul){
			ul[0].style.height = 0;
			$('#betterSelect_maximize\\:' + pos).removeClass('betterSelect-maximize-state-expanded');
			ul.removeClass('betterSelect-state-expanded');
			ul.find('.betterSelect-it').removeClass('betterSelect-it-hover');
		}


		/**
		 * Processes a click on an item of a 'betteSelect' control
		 * @param elem The clicked item
		 */
		function changeSelectSingle(elem) {
			var ul = $(elem[0].parentNode.parentNode);
			var id = elem[0].id;
			pos = id.substr(id.indexOf(':') + 1).split('.');
			var it = $.fn.betterSelects.self[pos[0]].options[pos[1]];
			// updates the preview with the content of label of the selected item
			ul.siblings('.betterSelect-preview')[0].innerHTML = it.innerHTML;
			ul.find('.betterSelect-it').removeClass('betterSelect-it-state-selected');
			elem.addClass('betterSelect-it-state-selected');
			// updates the original HTML select-element with the current selection
			it.selected = 'selected';
		}


		/**
		 * Adds handlers for common behaviors for both select types: single and multiple
		 */
		function initCommon(selectsBoxes, items){

			// Handler to expand/collapse the 'betterSelect' controls
			selectsBoxes.click(function(evt){
				pos = this.id.substr(this.id.indexOf(':') + 1);
				changeSelectMaximizeState(pos);
			});

			items.filter(':last-child').addClass('betterSelect-it-last');
		}

		
		/**
		 * Adds handlers for single-selects' peculiar behaviors
		 */
		function initSingles(selectBoxes, items){
			
			items.click(function(evt){
				changeSelectSingle($(this));
			});
			
			items.hover(function(){
				$(this.parentNode.parentNode).find('.betterSelect-it').removeClass('betterSelect-it-hover');
				$(this).addClass('betterSelect-it-hover');
			}, function(){
				$(this.parentNode.parentNode).find('.betterSelect-it').removeClass('betterSelect-it-hover');
			});
		}
		

		// Read all the created 'betterSelect' controls which have not been yet processed
		selectsBoxes = $('.betterSelect-box:not(.betterSelect-box-processed)');
		items = selectsBoxes.find('.betterSelect-it');

		// Adds handlers for common behaviors of both select types: single and multiple
		initCommon(selectsBoxes, items);
		
		// Adds handlers for single-selects' peculiar behaviors
		initSingles(selectsBoxes, items);

		// Marks controls as processed
		selectsBoxes.addClass('betterSelect-box-processed');
	};

})(jQuery);

CSS sourcode v0.5:

.betterSelect-box {
	overflow: auto;	
	margin: 0.5em 0;
	width: auto;
}
.betterSelect-preview {
	cursor: pointer;
	float: left;
	padding: 0.1em 0.3em;
	background: none repeat scroll 0 0 #fff;
	border: 1px solid #BBB;
	margin: 0;
	border-radius: 4px;
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
}
.betterSelect-maximize {
	float: left;
	cursor: pointer;
	height: 20px;
	width: 20px;
	background: url("../images/expand.png") no-repeat scroll 0 0 transparent;
}
.betterSelect-maximize-state-expanded {
	background-position: 0 -21px;
}
.betterSelect {
	position: absolute;
	border: 0 none;
	margin: 0;
	padding: 0;
	list-style: none none;
	overflow: auto;
	background: none repeat scroll 0 0 #FEAA25;
	color: #FFF;
	opacity: 0.95;
	filter: alpha(opacity=95);
	-ms-filter: "alpha(opacity=95)";
	border-radius: 2px 2px 6px 6px;
	-moz-border-radius: 2px 2px 6px 6px;
	-webkit-border-radius: 2px 2px 6px 6px;
}
.betterSelect-state-expanded {
	padding: 2px 0 1px 0;
	border: 1px solid #BBB;
	border-top: 1px inset;
}
.betterSelect-nc {
	float: left;
}
.betterSelect-it {
	width: auto;
	margin: 0 4px 4px 4px;
	padding: 4px 2px 6px 0;
	overflow: hidden;
	cursor: pointer;
	border-radius: 4px;
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
}
.betterSelect-it-hover {
	background-color: #FF7F2A;
}
.betterSelect-it-last {
	margin: 0 4px;
}
.betterSelect-it-val, .betterSelect-it-label {
	height: 14px;
	display: block;
	float: left;
}
.betterSelect-it-label {
	padding: 0 0 0 5px;
}
.betterSelect-it-val {
	background: url("../images/check.png") no-repeat scroll 0 0 transparent;
	width: 14px;
}
.betterSelect-it-state-selected &gt; .betterSelect-it-val  {
	background-position: 0 -14px;
}
.accesible-hidden-element {
	position: absolute;
	left: -1999px;
}

jquery.synchHeights an introductory plugin to the jQuery-plugins-creation world

leave a comment »

This time I’m going to “move a bit back in the time” in order to show how to create a very basic jQuery plugin, hopefully, it will be useful for those persons looking to get into the jQuery-plugins-creation world.

The plugin is intended to synchronize the heights of the elements matched by the given CSS selector.
The functionality is going to be very simple, it will just assign the tallest element’s height to all the
elements in the set. It should take advantage of all the power of the jQuery selectors and its usage
should be very straightforward, in short, something like that:

$('.element1-class, #element2_id', more_CSS_selectors').synchHeights();

So, lets go to the action:

/**
 * jQuery.synchHeights plugin v1.0
 * Copyright 2010, Roger Padilla - @rogerjose81@gmail.com
 * Licensed under Apache License 2.0
 * This plugin is intended to synchronize the heights of the elements matched
 * by the given CSS selector. The functionality of this plugin is very simple,
 * it just assigns the tallest element's height to all the elements in the set.
 */
$.fn.synchHeights = function() {

	// the 'this' object is a jQuery object which keep reference to DOM-elements in the set
	var elemsSet = this;
	
	// calls the function which obtains the greater hight
	var maxHeight = getMaximumHeight(elemsSet);
	
	// calls the function used to synchronize the heights
	synchHeights(elemsSet, maxHeight);
	

	// loops through the elements set to obtain the greater height
	function getMaximumHeight(elemsSet){
		var maxHeight = 0, item;
		elemsSet.each(function(){
			item = $(this);
			if (item.height() > maxHeight) {
				maxHeight = item.height();
			}
		});
		return maxHeight;
	}

	/*
	 * Synchronizes the heights of the elements in the set by using
	 * the calculated maximun-height
	 */
	function synchHeights(elemsSet, maxHeight) {
		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) {
			elemsSet.css({'height': maxHeight});
		}
		elemsSet.css({'min-height': maxHeight});
	}

	// returns 'this' to be able to use chaining selectors
	return this;
};

Written by roger.padilla

July 20, 2010 at 13:15

jquery.synchHeights un plugin introductorio al mundo de la creación de plugins jQuery

leave a comment »

Esta vez voy a “retroceder un poco en el tiempo” con el fin de mostrar cómo crear un plug-in jQuery muy básico, con suerte, será útil para aquellas personas que buscan entrar en el mundo de la creación de plug-ins jQuery.

synchHeights está diseñado para sincronizar las alturas de los elementos HTML que coincidan con el selector CSS dado.

La funcionalidad va a ser muy básica, se asignará la altura del elemento más alto a todos los elementos del conjunto. Este plugin debe aprovechar el poder de los selectores de jQuery y la forma de usarlo debe ser muy sencilla, en fin, será algo así:

$('.elemento1-class, #elemento2_id, mas_selectores_CSS').synchHeights();

Entonces, comencemos con la acción:

/**
 * jQuery.synchHeights plugin v1.0
 * Copyright 2010, Roger Padilla - @rogerjose81@gmail.com
 * Licenciado bajo Apache Licence v 2.0
 * Este plug-in sincroniza las alturas de los elementos seleccionados por el selector CSS dado
 */
$.fn.synchHeights = function() {

	// el objeto 'this' es un objeto jQuery el cual mantiene referencias a los elementos del DOM en el conjunto
	var elemsSet = this;
	
	
	// llamado a la función que obtiene la mayor altura
	var maxHeight = getMaximumHeight(elemsSet);
	
	// llamado a la función que sincroniza las alturas de los elementos
	synchHeights(elemsSet, maxHeight);
	

	// recorre cada elemento en el conjunto en búsqueda de la mayor altura
	function getMaximumHeight(elemsSet){
		var maxHeight = 0, item;
		elemsSet.each(function(){
			item = $(this);
			if (item.height() > maxHeight) {
				maxHeight = item.height();
			}
		});
		return maxHeight;
	}

	/*
	 * Sincroniza las altura de los elementos del conjunto con la mayor altura calculada previamente
	 */
	function synchHeights(elemsSet, maxHeight) {
		// para IE6, usamos la propiedad 'height' ya que ese navegador no soporta 'min-height'
		if ($.browser.msie && $.browser.version == 6.0) {
			elemsSet.css({'height': maxHeight});
		}
		elemsSet.css({'min-height': maxHeight});
	}

	// retornamos el objeto 'this' para poner usar selectores concatenados
	return this;
};

“busyBox”, a simpler and cooler AJAX-Loader jQuery plugin

with 8 comments

This time I’m going to show how to create a jQuery plugin. For such purpose, I’ve thought in something simple, nice and overall, useful. With that premise in mind, lets create a plugin to make appears some HTML boxes as “busy” (useful for example, while performing an AJAX request to update some section or block of a page), thus lets name this plugin as busyBox (v1.1 released at 2010-10-12).

Yes, out there exists several plugins intended to achieved something like that. The problem I see about these plugins is they puts a transparent layer over the entire page; but which I’m wanting for, is just to put an individual transparent layer over the involved boxes in the background process. The main advantages of this technique are: the user will be able to perform other actions while waiting for others being executed, further, the user will specifically know which sections of the page are being updated without breaks his navigation workflow, and at last but not at least, the user will see a cooler effect 😉

Which I’m looking for, is to be able to use the plugin in the following way:


var box= $('my-selector');

// Show the 'busy boxes' passing some configuration
box.busyBox(
  spinner: '<img src="path-to-the-image.gif" />'
);

$.ajax(
  url: 'my-url',
  success: function(response){
    box.html(response);
  },
  complete: function(){
    // Closes the 'busy boxes'
    box.busyBox('close');
  }
);

Lets know the basic structure of a jQuery plugin:

(function($) {

  // Using this, you'll be able to use your plugin using all the jQuery's power
  $.fn.myPluginName = function() {

    // Returning "this" is needed to be able to use chaining
    return this;
  };

})(jQuery);

Now that we know the basic structure of a plugin, lets go to the action creating our own.

As first step, lets create the basic structure of our plugin:

(function($) {

 /**
  * Main function; used to initialize the plugin or for calling the available functions provides by the plugin (such as 'open' or 'close').
  * We are going to use the 'arguments' array to obtain the passed parameters
  */
  $.fn.busyBox = function() {

    if(arguments[0] == 'open') {
      // some code to put the "busy boxes" over the wanted sections of the page
    } else if(arguments[0] == 'close') {
      // some code to close the previously-opened "busy boxes"
    } else {
      // some code to initialize the plugin
    }

    // Returning "this" is needed to be able to use chaining
    return this;
  };

})(jQuery);

As second step, wold be useful to make our plugin configurable, thus, lets create some default configuration:

(function($) {

 /**
  * Main function; used to initialize the plugin or for calling the available functions provides by the plugin (such as 'open' or 'close').
  * We are going to use the 'arguments' array to obtain the passed parameters
  */
  $.fn.busyBox = function() {

    if(arguments[0] == 'open') {
      // some code to put the "busy boxes" over the wanted sections of the page
    } else if(arguments[0] == 'close') {
      // some code to close the previously-opened "busy boxes"
    } else {
      // some code to initialize the plugin
    }

    // Returning "this" is needed to be able to use chaining
    return this;
  };

 /**
  * Default configuration
  */
  $.fn.busyBox.defaults = {
    autoOpen: true,
    spinner: '<em>Loading...</em>',
    classes: 'busybox',
    top: 'auto',
    left: 'auto'
  };

})(jQuery);

As third step, lets create the basic structure of all our functions:

(function($) {
 /**
  * Main function; used to initialize the plugin or for calling the available functions provides by the plugin (such as 'open' or 'close').
  * We are going to use the 'arguments' array to obtain the passed parameters
  */
  $.fn.busyBox = function() {

    $.fn.busyBox.self = this;

    if(arguments[0] == 'open') {
      $.fn.busyBox.open();
    } else if(arguments[0] == 'close') {
      $.fn.busyBox.close();
    } else {
      $.fn.busyBox.init(arguments[0]);
    }

    return this;
  };

 /**
  * Initialize the plugin using the passed options
  */
  $.fn.busyBox.init = function(options) {

    $.fn.busyBox.opts = $.extend({}, $.fn.busyBox.defaults, options);

    // Adds the default classes if they are not present in the passed classes
    if($.fn.busyBox.opts.classes.indexOf($.fn.busyBox.defaults.classes) === -1){
      $.fn.busyBox.opts.classes += ' ' + $.fn.busyBox.defaults.classes;
    }

    $.fn.busyBox.container = $(document.body);

    if($.fn.busyBox.opts.autoOpen){
      $.fn.busyBox.open();
    }
  };

 /**
  * Display all the 'busyBoxes' over the matched boxes
  */
  $.fn.busyBox.open = function(){
    // some code to display the "busy boxes" effect
  };

 /**
  * Closes all the 'busyBoxes' being showed
  */
  $.fn.busyBox.close = function(){
    // some code to quit the "busy boxes" effect
  };

 /**
  * Default configuration
  */
  $.fn.busyBox.defaults = {
    autoOpen: true,
    spinner: '<em>Loading…</em>',
    classes: 'busybox',
    top: 'auto',
    left: 'auto'
  };

})(jQuery);

Now, putting together all the JavaScript code:

/**
 * 'busyBox' v1.1
 * @author Roger Padilla C. - rogerjose81@gmail.com
 * Web: https://rogerpadilla.wordpress.com/2010/05/24/jquery-busybox/
 * Licensed under Apached License v2.0
 */
(function($) {

	/**
	 * Main function; used to initialize the plugin or for calling the available functionalities of the plugin (such as 'open' or 'close').
	 * The 'arguments' array is used to obtain the received parameters
	 */
	$.fn.busyBox = function() {

		$.fn.busyBox.self = this;

		if(arguments[0] == 'open') {
			$.fn.busyBox.open();
		} else if(arguments[0] == 'close') {
			$.fn.busyBox.close();
		} else {
			$.fn.busyBox.init(arguments[0]);
		}

		return this;
	};

	/**
	 * Initialize the plugin using the passed options
	 */
	$.fn.busyBox.init = function(options) {

		$.fn.busyBox.opts = $.extend({}, $.fn.busyBox.defaults, options);

		// Adds the default classes if they are not present in the passed classes
		if($.fn.busyBox.opts.classes.indexOf($.fn.busyBox.defaults.classes) === -1){
			$.fn.busyBox.opts.classes += ' ' + $.fn.busyBox.defaults.classes;
		}

		$.fn.busyBox.container = $(document.body);

		if($.fn.busyBox.opts.autoOpen){
			$.fn.busyBox.open();
		}
	};

	/**
	 * Display all the 'busyBoxes' over the matched boxes
	 */
	$.fn.busyBox.open = function(){

		var box, inner, e, bOffset, bWidth, bHeight, iTop, iLeft;

		$.fn.busyBox.self.each(function(index) {

			e = $(this);
			bWidth = e.outerWidth();
			bHeight = e.outerHeight();
			bOffset = e.offset();

			box = $('<div />');
			box.attr('id', 'busybox_' + index);
			box.addClass($.fn.busyBox.opts.classes);

			box.css({
				width: bWidth,
				height: bHeight,
				top: bOffset.top,
				left: -9999 // Used to not display the box yet without hidden it (needed to be able to calculate its dimensions)
			});

			inner = $($.fn.busyBox.opts.spinner);
			inner.attr('id', 'busybox_spinner_' + index);
			inner.addClass('busybox-spinner');

			box.append(inner);

			$.fn.busyBox.container.append(box);

			// Set the position of the inner message inside its parent. Calculates the 'top' and/or 'left' coordinates of the inner-message (inside its parent) if those properties were configured as 'auto'
			iTop = ($.fn.busyBox.opts.top == 'auto' ? ((bHeight / 2) - (inner.outerHeight() / 2)) + 'px' : $.fn.busyBox.opts.top);
			iLeft = ($.fn.busyBox.opts.left == 'auto' ? ((bWidth / 2) - (inner.outerWidth() / 2)) + 'px' : $.fn.busyBox.opts.left);

			inner.css({
				position: 'absolute',
				top: iTop,
				left: iLeft,
				opacity: 1.0
			});

			// Hidde and relocate the 'busyBox' (previously displayed using a negative left-coord to be able to calculate its dimensions)
			box.css({display: 'none', left: bOffset.left});
		});

		// Display all the 'busyBoxes'
		$.fn.busyBox.container.find('.' + $.fn.busyBox.defaults.classes).fadeIn('fast', $.fn.busyBox.opts.displayed.call(this));
	};

	/**
	 * Closes all the 'busyBoxes' being showed
	 */
	$.fn.busyBox.close = function(){
		if($.fn.busyBox.container) {
			$.fn.busyBox.container.find('.' + $.fn.busyBox.defaults.classes).fadeOut('fast', function(){
				$(this).remove();
			});
		}
	};

	/**
	 * Default configuration
	 */
	$.fn.busyBox.defaults = {
		autoOpen: true,
		spinner: '<em>Cargando…</em>',
		classes: 'busybox',
		top: 'auto',
		left: 'auto',
		displayed: function(){}
	};

})(jQuery);

a bit of CSS and we are done!

.busybox {
	position: absolute;
	z-index: 999;
	color: #fff;
	background-color: #666;
	margin: 0;
	padding: 0;
	opacity: 0.5;
	filter: alpha(opacity=95);
	-ms-filter: "alpha(opacity=95)";
}

Screenshot:

Written by roger.padilla

May 24, 2010 at 10:49