jQuery popup plugin


/ Published in: JavaScript
Save to your folder(s)

Another popup jQuery plugin implementation complying with YAGNI.


Copy this code and paste it in your HTML
  1. (function() {
  2.  
  3. /**
  4.   * overlay element
  5.   */
  6. var mask = null;
  7.  
  8. /**
  9.   * create mask if it dose not exist
  10.   */
  11. function init() {
  12. mask || (mask = $('<div />', { 'id': 'mask' }).appendTo('body'));
  13. }
  14.  
  15. /**
  16.   * display modal
  17.   */
  18. function modal() {
  19. mask.css({
  20. 'width': $(document).width(),
  21. 'height': $(document).height()
  22. });
  23. mask.fadeIn('fast');
  24. }
  25.  
  26. /**
  27.   * display modal and open popup window
  28.   */
  29. function open() {
  30. var popup = $(this),
  31. win = $(window),
  32. top = win.height() / 2 - popup.height() / 2,
  33. left = win.width() / 2 - popup.width() / 2;
  34.  
  35. modal();
  36. popup.css({
  37. 'top': top,
  38. 'left': left
  39. });
  40. popup.fadeIn('fast');
  41. }
  42.  
  43. /**
  44.   * close modal and popup window
  45.   */
  46. function close() {
  47. var popup = $(this);
  48.  
  49. popup.hide();
  50. mask.hide();
  51. }
  52.  
  53. /**
  54.   * initialize popup plugin or execute method
  55.   * // initialize
  56.   * var popup = $('#popup').popup();
  57.   * // open popup
  58.   * popup.popup('open');
  59.   */
  60. $.fn.popup = function() {
  61. var methods = {
  62. open: open,
  63. close: close
  64. },
  65. m = methods[arguments[0]];
  66.  
  67. if (m) {
  68. // method call
  69. m.apply(this, arguments);
  70. } else {
  71. // initialization
  72. init.apply(null, arguments);
  73. }
  74. return this;
  75. };
  76. }());

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.