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?

   jQuery.fn.showAlert = function(text, duration, opacity, inSpeed, outSpeed, width) {
       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>";
       $(this).append(content);
       var mask = $("#mask");
       mask.css({ 'position': 'absolute',
           'z-index': 9000,
           'background-color': '#000',
           'top': '0px',
           'left': '0px',
          'opacity': 0
      });
  
      var dialogContainer = $("#boxes");
      dialogContainer.css({ 'width': width,
          'height': '250px'
      });
  
      var dialog = $("#dialog");
      dialog.css({
          'position': 'absolute',
          'z-index': 9999,
          'background-color': '#ffffff',
          'top': '0px',
          'left': '0px',
          'padding': '5px',
          'border': 'solid 2px black',
          'width': width
      });
      dialog.hide();
  
      var maskHeight = $(document).height();
      var maskWidth = $(document).width();
  
      var dialogTop = ($(window).height() - dialog.height()) / 2 + $(window).scrollTop() + "px";
      var dialogLeft = ($(window).width() - dialog.width()) / 2 + $(window).scrollLeft() + "px";
  
      dialog.css({ 'top': dialogTop, 'left': dialogLeft });
  
      mask.css({ 'width': maskWidth, 'height': maskHeight });
      mask.fadeTo(inSpeed, opacity);
  
      dialog.fadeIn(inSpeed);
  
      var close = $("#close");
      if (duration < 0) {
          close.css({ 'cursor': 'pointer' }).click(function() {
              var newSpeed = outSpeed / 2;
              dialog.fadeOut(newSpeed, function() {
                  mask.fadeOut(newSpeed, function() {
                      $("#alert").remove();
                  });
              });
          });
      }
      else {
          close.hide();
          window.setTimeout(function() {
              var newSpeed = outSpeed / 2;
              dialog.fadeOut(newSpeed, function() {
                  mask.fadeOut(newSpeed, function() {
                      $("#alert").remove();
                  });
              });
          }, duration);
      }
  }
  
Advertisements

One thought on “jQuery Modal Display Optimization

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s