Skip to content

Instantly share code, notes, and snippets.

@danrichards
Last active February 21, 2016 04:48
Show Gist options
  • Save danrichards/46e89a9911fd990541c7 to your computer and use it in GitHub Desktop.
Save danrichards/46e89a9911fd990541c7 to your computer and use it in GitHub Desktop.
jQuery / Handlebars alert plugin for Bootstrap.
/**
* @author Dan Richards <drichards@shapeup.com>
*
* Assumes a compiled handlebars template is available.
* @see http://handlebarsjs.com/precompilation.html
*/
(function ($) {
$.extend({
alert: function(message, params) {
var alertContainer = $('#alerts');
alertContainer.show();
if (typeof params == 'undefined') {
params = {
'type': 'danger',
'dismissable': true,
'append': true
}
} else {
params.type = typeof params.type == 'undefined' ? 'danger' : params.type;
params.append = typeof params.append == 'undefined' ? true : params.append;
params.dismissable = typeof params.dismissable == 'undefined' ? true : params.dismissable;
}
params.message = message;
var alert = Handlebars.templates.alert(params);
if (params.append) {
$(alert).appendTo('#alerts');
} else {
alertContainer.text(alert);
}
}
});
})(jQuery);
/**
* Hide the alerts container if there are no alerts left.
*/
$(document).on('click', 'button[data-dismiss="alert"]', function(){
if ($('#alerts').text() == "") {
$('#alerts').hide();
}
});
<div class="alert alert-{{type}} alert-dismissible" role="alert">
{{#if dismissable}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
{{/if}}
{{message}}
</div>

In your html layout

<div id="alerts" style="display:none;"></div>

Call with jquery

$.alert("Ut oh, there was an error.", {'type': 'success'});

Call with jquery and no params.

$.alert("Ut oh, there was an error.");

Default params as follows:

{
  'type': 'danger',
  'append': true,
  'dismissable': true
}

Hide the container when empty

This will be useful if you want to hide the #alerts div while empty.

/**
 * Hide the alerts container if there are no alerts left.
 */
$(document).on('click', 'button[data-dismiss="alert"]', function(){
    if ($('#alerts').text() == "") {
        $('#alerts').hide();
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment