Skip to content

Instantly share code, notes, and snippets.

@Fardinak
Last active December 23, 2015 02:49
Show Gist options
  • Save Fardinak/6569593 to your computer and use it in GitHub Desktop.
Save Fardinak/6569593 to your computer and use it in GitHub Desktop.
A multi-alert handler, with show/hide/timeout/dismiss functionality; developed based on Twitter Bootstrap's alert styling, but easy to modify. It's using jQuery, but a vanilla implementation is easy to achieve.
/** @constructor */
window.alertbox = new (function($, window, undefined) {
var $alb = $('<div id="alertbox" class="alert">').hide().appendTo('body')
, timer = null
, next = [];
/**
* Enum for alert types and their respective class names
*
* @public
* @enum {String}
*/
this.type = {
info : 'alert-info',
success : 'alert-success',
warning : 'alert-warning',
error : 'alert-danger'
};
/**
* @private
* @constant {(alertbox.type|Sting)}
* @default
*/
var DEFAULT_STATE = alertbox.type.info;
/**
* @private
* @constant {number}
* @default
*/
var DEFAULT_INTERVAL = 8000;
/**
* Removes all existing type-classes and replace the
* provided one whether it is a type (e.g. error) or
* it's respective class name (e.g. alert-danger)
*
* @private
* @param {!(alertbox.type|String)} type
*/
function _setType(type) {
var matchesValue = false;
type = type.toLowerCase();
for(var key in alertbox.type) {
$alb.removeClass(alertbox.type[key]);
if(alertbox.type[key] === type) matchesValue = true;
}
if(matchesValue) $alb.addClass(type);
else if(type in alertbox.type) $alb.addClass(alertbox.type[type]);
}
/**
* Fetch the next alert message and show it (FIFO)
*
* @private
*/
function _next() {
if(next.length > 0) alertbox.show(next.shift());
}
/**
* Show a new alert or stor it if another one is
* being shown
*
* @public
* @param {!(string|Object)} message - A message string or an Alert object
* @param {(alertbox.type|String)} [type]
* @param {Number} [interval]
*/
this.show = function(msg, type, interval) {
if(msg instanceof Object) {
interval = msg.interval;
type = msg.type;
msg = msg.msg;
}
if(type == undefined) type = DEFAULT_STATE;
if(interval == undefined) interval = DEFAULT_INTERVAL;
if(timer == null) {
_setType(type);
$alb.html(msg);
$alb.slideDown('fast');
if(interval) timer = setTimeout(alertbox.hide, parseInt(interval));
} else {
next.push({msg: msg, type: type, interval: interval});
}
};
/**
* Dismiss the current alert and possibly all that's left
*
* @public
* @param {Boolean} [noMore] - Dismiss all
*/
this.dismiss = function(noMore) {
if(noMore) next.length = 0;
alertbox.hide();
};
/**
* Hide the current alert and display the next (if any)
*
* @public
*/
this.hide = function() {
$alb.slideUp('fast', _next);
clearTimeout(timer);
timer = null;
};
})(jQuery, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment