jquery.gritter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. * Gritter for jQuery
  3. * http://www.boedesign.com/
  4. *
  5. * Copyright (c) 2012 Jordan Boesch
  6. * Dual licensed under the MIT and GPL licenses.
  7. *
  8. * Date: February 24, 2012
  9. * Version: 1.7.4
  10. */
  11. (function($){
  12. /**
  13. * Set it up as an object under the jQuery namespace
  14. */
  15. $.gritter = {};
  16. /**
  17. * Set up global options that the user can over-ride
  18. */
  19. $.gritter.options = {
  20. position: '',
  21. class_name: '', // could be set to 'gritter-light' to use white notifications
  22. fade_in_speed: 'medium', // how fast notifications fade in
  23. fade_out_speed: 1000, // how fast the notices fade out
  24. time: 6000 // hang on the screen for...
  25. }
  26. /**
  27. * Add a gritter notification to the screen
  28. * @see Gritter#add();
  29. */
  30. $.gritter.add = function(params){
  31. try {
  32. return Gritter.add(params || {});
  33. } catch(e) {
  34. var err = 'Gritter Error: ' + e;
  35. (typeof(console) != 'undefined' && console.error) ?
  36. console.error(err, params) :
  37. alert(err);
  38. }
  39. }
  40. /**
  41. * Remove a gritter notification from the screen
  42. * @see Gritter#removeSpecific();
  43. */
  44. $.gritter.remove = function(id, params){
  45. Gritter.removeSpecific(id, params || {});
  46. }
  47. /**
  48. * Remove all notifications
  49. * @see Gritter#stop();
  50. */
  51. $.gritter.removeAll = function(params){
  52. Gritter.stop(params || {});
  53. }
  54. /**
  55. * Big fat Gritter object
  56. * @constructor (not really since its object literal)
  57. */
  58. var Gritter = {
  59. // Public - options to over-ride with $.gritter.options in "add"
  60. position: '',
  61. fade_in_speed: '',
  62. fade_out_speed: '',
  63. time: '',
  64. // Private - no touchy the private parts
  65. _custom_timer: 0,
  66. _item_count: 0,
  67. _is_setup: 0,
  68. _tpl_close: '<div class="gritter-close"></div>',
  69. _tpl_title: '<span class="gritter-title">[[title]]</span>',
  70. _tpl_item: '<div id="gritter-item-[[number]]" class="gritter-item-wrapper [[item_class]]" style="display:none"><div class="gritter-top"></div><div class="gritter-item">[[close]][[image]]<div class="[[class_name]]">[[title]]<p>[[text]]</p></div><div style="clear:both"></div></div><div class="gritter-bottom"></div></div>',
  71. _tpl_wrap: '<div id="gritter-notice-wrapper"></div>',
  72. /**
  73. * Add a gritter notification to the screen
  74. * @param {Object} params The object that contains all the options for drawing the notification
  75. * @return {Integer} The specific numeric id to that gritter notification
  76. */
  77. add: function(params){
  78. // Handle straight text
  79. if(typeof(params) == 'string'){
  80. params = {text:params};
  81. }
  82. // We might have some issues if we don't have a title or text!
  83. if(!params.text){
  84. throw 'You must supply "text" parameter.';
  85. }
  86. // Check the options and set them once
  87. if(!this._is_setup){
  88. this._runSetup();
  89. }
  90. // Basics
  91. var title = params.title,
  92. text = params.text,
  93. image = params.image || '',
  94. sticky = params.sticky || false,
  95. item_class = params.class_name || $.gritter.options.class_name,
  96. position = $.gritter.options.position,
  97. time_alive = params.time || '';
  98. this._verifyWrapper();
  99. this._item_count++;
  100. var number = this._item_count,
  101. tmp = this._tpl_item;
  102. // Assign callbacks
  103. $(['before_open', 'after_open', 'before_close', 'after_close']).each(function(i, val){
  104. Gritter['_' + val + '_' + number] = ($.isFunction(params[val])) ? params[val] : function(){}
  105. });
  106. // Reset
  107. this._custom_timer = 0;
  108. // A custom fade time set
  109. if(time_alive){
  110. this._custom_timer = time_alive;
  111. }
  112. var image_str = (image != '') ? '<img src="' + image + '" class="gritter-image" />' : '',
  113. class_name = (image != '') ? 'gritter-with-image' : 'gritter-without-image';
  114. // String replacements on the template
  115. if(title){
  116. title = this._str_replace('[[title]]',title,this._tpl_title);
  117. }else{
  118. title = '';
  119. }
  120. tmp = this._str_replace(
  121. ['[[title]]', '[[text]]', '[[close]]', '[[image]]', '[[number]]', '[[class_name]]', '[[item_class]]'],
  122. [title, text, this._tpl_close, image_str, this._item_count, class_name, item_class], tmp
  123. );
  124. // If it's false, don't show another gritter message
  125. if(this['_before_open_' + number]() === false){
  126. return false;
  127. }
  128. $('#gritter-notice-wrapper').addClass(position).append(tmp);
  129. var item = $('#gritter-item-' + this._item_count);
  130. item.fadeIn(this.fade_in_speed, function(){
  131. Gritter['_after_open_' + number]($(this));
  132. });
  133. if(!sticky){
  134. this._setFadeTimer(item, number);
  135. }
  136. // Bind the hover/unhover states
  137. $(item).bind('mouseenter mouseleave', function(event){
  138. if(event.type == 'mouseenter'){
  139. if(!sticky){
  140. Gritter._restoreItemIfFading($(this), number);
  141. }
  142. }
  143. else {
  144. if(!sticky){
  145. Gritter._setFadeTimer($(this), number);
  146. }
  147. }
  148. Gritter._hoverState($(this), event.type);
  149. });
  150. // Clicking (X) makes the perdy thing close
  151. $(item).find('.gritter-close').click(function(){
  152. Gritter.removeSpecific(number, {}, null, true);
  153. });
  154. return number;
  155. },
  156. /**
  157. * If we don't have any more gritter notifications, get rid of the wrapper using this check
  158. * @private
  159. * @param {Integer} unique_id The ID of the element that was just deleted, use it for a callback
  160. * @param {Object} e The jQuery element that we're going to perform the remove() action on
  161. * @param {Boolean} manual_close Did we close the gritter dialog with the (X) button
  162. */
  163. _countRemoveWrapper: function(unique_id, e, manual_close){
  164. // Remove it then run the callback function
  165. e.remove();
  166. this['_after_close_' + unique_id](e, manual_close);
  167. // Check if the wrapper is empty, if it is.. remove the wrapper
  168. if($('.gritter-item-wrapper').length == 0){
  169. $('#gritter-notice-wrapper').remove();
  170. }
  171. },
  172. /**
  173. * Fade out an element after it's been on the screen for x amount of time
  174. * @private
  175. * @param {Object} e The jQuery element to get rid of
  176. * @param {Integer} unique_id The id of the element to remove
  177. * @param {Object} params An optional list of params to set fade speeds etc.
  178. * @param {Boolean} unbind_events Unbind the mouseenter/mouseleave events if they click (X)
  179. */
  180. _fade: function(e, unique_id, params, unbind_events){
  181. var params = params || {},
  182. fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
  183. fade_out_speed = params.speed || this.fade_out_speed,
  184. manual_close = unbind_events;
  185. this['_before_close_' + unique_id](e, manual_close);
  186. // If this is true, then we are coming from clicking the (X)
  187. if(unbind_events){
  188. e.unbind('mouseenter mouseleave');
  189. }
  190. // Fade it out or remove it
  191. if(fade){
  192. e.animate({
  193. opacity: 0
  194. }, fade_out_speed, function(){
  195. e.animate({ height: 0 }, 300, function(){
  196. Gritter._countRemoveWrapper(unique_id, e, manual_close);
  197. })
  198. })
  199. }
  200. else {
  201. this._countRemoveWrapper(unique_id, e);
  202. }
  203. },
  204. /**
  205. * Perform actions based on the type of bind (mouseenter, mouseleave)
  206. * @private
  207. * @param {Object} e The jQuery element
  208. * @param {String} type The type of action we're performing: mouseenter or mouseleave
  209. */
  210. _hoverState: function(e, type){
  211. // Change the border styles and add the (X) close button when you hover
  212. if(type == 'mouseenter'){
  213. e.addClass('hover');
  214. // Show close button
  215. e.find('.gritter-close').show();
  216. }
  217. // Remove the border styles and hide (X) close button when you mouse out
  218. else {
  219. e.removeClass('hover');
  220. // Hide close button
  221. e.find('.gritter-close').hide();
  222. }
  223. },
  224. /**
  225. * Remove a specific notification based on an ID
  226. * @param {Integer} unique_id The ID used to delete a specific notification
  227. * @param {Object} params A set of options passed in to determine how to get rid of it
  228. * @param {Object} e The jQuery element that we're "fading" then removing
  229. * @param {Boolean} unbind_events If we clicked on the (X) we set this to true to unbind mouseenter/mouseleave
  230. */
  231. removeSpecific: function(unique_id, params, e, unbind_events){
  232. if(!e){
  233. var e = $('#gritter-item-' + unique_id);
  234. }
  235. // We set the fourth param to let the _fade function know to
  236. // unbind the "mouseleave" event. Once you click (X) there's no going back!
  237. this._fade(e, unique_id, params || {}, unbind_events);
  238. },
  239. /**
  240. * If the item is fading out and we hover over it, restore it!
  241. * @private
  242. * @param {Object} e The HTML element to remove
  243. * @param {Integer} unique_id The ID of the element
  244. */
  245. _restoreItemIfFading: function(e, unique_id){
  246. clearTimeout(this['_int_id_' + unique_id]);
  247. e.stop().css({ opacity: '', height: '' });
  248. },
  249. /**
  250. * Setup the global options - only once
  251. * @private
  252. */
  253. _runSetup: function(){
  254. for(opt in $.gritter.options){
  255. this[opt] = $.gritter.options[opt];
  256. }
  257. this._is_setup = 1;
  258. },
  259. /**
  260. * Set the notification to fade out after a certain amount of time
  261. * @private
  262. * @param {Object} item The HTML element we're dealing with
  263. * @param {Integer} unique_id The ID of the element
  264. */
  265. _setFadeTimer: function(e, unique_id){
  266. var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
  267. this['_int_id_' + unique_id] = setTimeout(function(){
  268. Gritter._fade(e, unique_id);
  269. }, timer_str);
  270. },
  271. /**
  272. * Bring everything to a halt
  273. * @param {Object} params A list of callback functions to pass when all notifications are removed
  274. */
  275. stop: function(params){
  276. // callbacks (if passed)
  277. var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
  278. var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};
  279. var wrap = $('#gritter-notice-wrapper');
  280. before_close(wrap);
  281. wrap.fadeOut(function(){
  282. $(this).remove();
  283. after_close();
  284. });
  285. },
  286. /**
  287. * An extremely handy PHP function ported to JS, works well for templating
  288. * @private
  289. * @param {String/Array} search A list of things to search for
  290. * @param {String/Array} replace A list of things to replace the searches with
  291. * @return {String} sa The output
  292. */
  293. _str_replace: function(search, replace, subject, count){
  294. var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
  295. f = [].concat(search),
  296. r = [].concat(replace),
  297. s = subject,
  298. ra = r instanceof Array, sa = s instanceof Array;
  299. s = [].concat(s);
  300. if(count){
  301. this.window[count] = 0;
  302. }
  303. for(i = 0, sl = s.length; i < sl; i++){
  304. if(s[i] === ''){
  305. continue;
  306. }
  307. for (j = 0, fl = f.length; j < fl; j++){
  308. temp = s[i] + '';
  309. repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
  310. s[i] = (temp).split(f[j]).join(repl);
  311. if(count && s[i] !== temp){
  312. this.window[count] += (temp.length-s[i].length) / f[j].length;
  313. }
  314. }
  315. }
  316. return sa ? s : s[0];
  317. },
  318. /**
  319. * A check to make sure we have something to wrap our notices with
  320. * @private
  321. */
  322. _verifyWrapper: function(){
  323. if($('#gritter-notice-wrapper').length == 0){
  324. $('body').append(this._tpl_wrap);
  325. }
  326. }
  327. }
  328. })(jQuery);