18 November 2009

jQuery Modal Display Optimization

I have been doing a lot of work with jQuery lately and decided that I would create my own modal popup display. However, I want to look for ways to optimize this code, if there are any. Anyone have any suggestions?

  1: jQuery.fn.showAlert = function(text, duration, opacity, inSpeed, outSpeed, width) {
  2:     var content = "<div id=\"alert\"><div id=\"boxes\"><div id=\"dialog\" class=\"window\">" + text + "<div id=\"close\">OK</div></div></div><div id=\"mask\" name=\"modal\"></div></div>";
  3:     $(this).append(content);
  4:     var mask = $("#mask");
  5:     mask.css({ 'position': 'absolute',
  6:         'z-index': 9000,
  7:         'background-color': '#000',
  8:         'top': '0px',
  9:         'left': '0px',
 10:         'opacity': 0
 11:     });
 12: 
 13:     var dialogContainer = $("#boxes");
 14:     dialogContainer.css({ 'width': width,
 15:         'height': '250px'
 16:     });
 17: 
 18:     var dialog = $("#dialog");
 19:     dialog.css({
 20:         'position': 'absolute',
 21:         'z-index': 9999,
 22:         'background-color': '#ffffff',
 23:         'top': '0px',
 24:         'left': '0px',
 25:         'padding': '5px',
 26:         'border': 'solid 2px black',
 27:         'width': width
 28:     });
 29:     dialog.hide();
 30: 
 31:     var maskHeight = $(document).height();
 32:     var maskWidth = $(document).width();
 33: 
 34:     var dialogTop = ($(window).height() - dialog.height()) / 2 + $(window).scrollTop() + "px";
 35:     var dialogLeft = ($(window).width() - dialog.width()) / 2 + $(window).scrollLeft() + "px";
 36: 
 37:     dialog.css({ 'top': dialogTop, 'left': dialogLeft });
 38: 
 39:     mask.css({ 'width': maskWidth, 'height': maskHeight });
 40:     mask.fadeTo(inSpeed, opacity);
 41: 
 42:     dialog.fadeIn(inSpeed);
 43: 
 44:     var close = $("#close");
 45:     if (duration < 0) {
 46:         close.css({ 'cursor': 'pointer' }).click(function() {
 47:             var newSpeed = outSpeed / 2;
 48:             dialog.fadeOut(newSpeed, function() {
 49:                 mask.fadeOut(newSpeed, function() {
 50:                     $("#alert").remove();
 51:                 });
 52:             });
 53:         });
 54:     }
 55:     else {
 56:         close.hide();
 57:         window.setTimeout(function() {
 58:             var newSpeed = outSpeed / 2;
 59:             dialog.fadeOut(newSpeed, function() {
 60:                 mask.fadeOut(newSpeed, function() {
 61:                     $("#alert").remove();
 62:                 });
 63:             });
 64:         }, duration);
 65:     }
 66: }
 67: 

1 comment:

Webplore said...

Good one keep uploading such type of things will return to read your blog...
Web Development