Skip to content

Instantly share code, notes, and snippets.

@arturmamedov
Last active July 9, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturmamedov/0c0bf53c3286d8fd2e24 to your computer and use it in GitHub Desktop.
Save arturmamedov/0c0bf53c3286d8fd2e24 to your computer and use it in GitHub Desktop.
Show bootstrap 3/4 alerts like notifications or whatever you want simply by call `withAlert('message', 'type')`
/**
* withAlert()
*
* @dependencies [css: bootstrap(.alert), withstyle(.withAlert), jquery]
*
* @param string message
* @param string type warning|success|danger|primary|secondary|info
* @param object options {autohide: true/false, hidetime: 6000, placement: top|bottom}
*/
function withAlert(message, type, options) {
var defaults = {autohide: true, hidetime: 6000, placement: 'top'};
var opts = $.extend(defaults, options);
var zindex = 5001, posOffset = 70, alert_count = 1;
if (!message) {
message = 'Errore inaspettato. Scusate per il disagio. (Unexpected Error)';
}
if (!type) {
type = 'warning';
}
_alert_count = parseInt($(".withAlert").length);
if (_alert_count > 0) {
alert_count = _alert_count;
}
zindex = alert_count + 5001;
posOffset = alert_count * posOffset;
if (posOffset > 100) {
posOffset = 100 + (alert_count * 3);
if (posOffset > 150) {
posOffset = 150;
}
}
// here we create the bootstrap 4 alert code
var element = '<div class="withAlert alert alert-' + type + ' alert-dismissible fade show" style="z-index: ' + zindex + '; '+ opts.placement +': ' + posOffset + 'px;"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span class="message">' + message + '</span><div class="clearfix"></div></div>';
var eobj = $(element).clone();
$(eobj).appendTo("body");
if (opts.autohide) {
setTimeout(function () {
$(eobj).hide('slow', function () {
$(this).remove();
});
}, opts.hidetime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment