Dynamically create Bootstrap style alerts at run time.
I created BootstrapAlerts when working with AngularJS. I wanted a way to dynamically create alerts that would appear and vary in their information.
Early version involved writing HTML strings, parsing them, and then inserting them. You'd be right to look at me questioningly.
I realised that I could not sustain this.
I began working on a simple class that I could create to make these alerts at runtime.
My application would create a instance of the class and then set various options depending on AJAX requests.
BootstrapAlerts is a completely standalone library.
To include it in your site, add a script reference to the head of your document.
<script src="/path/to/bootstrap-alerts.js"></script>
Once the file is referenced it is very simple to create these alerts.
Below is a simple sample of code.
var ba = new BootstrapAlert();
ba.setBackground('success'); // set the alert to a success one
ba.addH(1, 'Action was successful!'); // create a heading 1 tag
ba.addP('The action you just performed was completed successfully.');
document.getElementByTagName('body')[0].appendChild(ba.render());
The above will generate a Bootstrap alert and append it to the body of the document.
Despite the library not requiring jQuery, it can still be used in the jQuery selector by calling render()
inside it.
For example $(ba.render())
would successfully create a jQuery instance of the alert.
In much the same way that jQuery options work; BootstrapAlerts accepts a JSON of options that it will overwrite the defaults with.
Before I begin explaining all of the options, I'll include a simple demonstration.
var ba = new BootstrapAlert({
dismissible: true,
background: 'primary'
});
If set to true, this will add the × character to the top right corner of the alert allowing it to be closed and dismissed.
This will cause the alert to fade into view rather than just appearing on the screen. In addition, if dimissible is set to true and the alert is closed then this will also fade the alert out.
The time, in milliseconds, before the alert will be destroyed from the DOM.
This requires that dimissible is set to true.
The reason for that choice is that I deemed it undesired behavious to destory an alert if it is unable to be deleted by the user.
This way, the user can destroy the element themselves with the × button or after a period of time it will go itself.
A natural number that specifies the maximum number of alerts that can be produced.
This is useful for when you want to create many alerts but not have too many on the screen.
Setting to 0 or below will disable this option.
This requires maxId to be set to a string of length more than 1.
This is so that JavaScript knows which alerts it is destroying of that type / ID.
Note: this is currently WIP.
The alerts deleted currently are those at the top of the DOM. That is, the alert at position 0
in the DOM (the highest alert in the DOM) will be deleted and not the oldest alert.
An identifier for the alert.
Alerts can have many different IDs, and can even have the same ID.
This is because it doesn't set the ID of the alert to this value, it will set the data-max-id
to this value, allowing multiple alerts to share the same ID thus being able to have a max
limit to restrict excessive alert usage.
One of the following values:
- primary
- secondary
- success
- danger
- warning
- info
- light
- dark
Note: The ordered list number values. The significance of these is that you can specify the number version for the background and that will select that background.
Post Note: If an invalid background is passed, the default value will be used instead.
For any extra classes that you want to apply to the alert.
This option can take multiple variable types, the below is how they are expected to be presented.
String
A space delimited string. That is, as if you were writing the class in the HTML.
'class1 class2 class3'
Array
An array where each value in the array is a new class.
['class1', 'class2', 'class3']
Object
An object where each value in the object is a new class.
{ 'class1', 'class2', 'class3' }
None.
True if no content has been added, false otherwise.
Note: This is the content of the alert, not whether options have been set. This means that an alert could have its background changed, but as long as no text is set then it is empty.
This clears all content not the styling of the alert.
None.
All functions from this point on will assume that they return this
, unless stated otherwise.
This return value is to allow for chaining methods.
bg
This is the same as passing a background to the options object; except this is done at runtime.
See thebackground
option for more information.
Alias of setBackground
.
str
The String that will overwrite the current content of the alert.
It is advised that you use one of the style functions below (such asaddP
) as this meant as a 'cover-all' solution for anything that you might want to do, but otherwise couldn't.
Note: This doesn't have to be HTML, but note that no validation is done to the string.
str
Similar to the above function. Except that this appends the content with pure HTML.
str
Any information that will be wrapped in<p>
tags.classes
optional
This can be used to give your paragraph any formatting such as'm-0 mt-1'
.
Alias of addParagraph
.
href
The location that the anchor will point to.text
optional
The text to display for the anchor.
If negated,text
will default tohref
.classes
optional
Any extra classes to apply to the anchor, such astext-primary
.target
optional
One of:blank
: Opens the linked document in a new window._self
: Opens the linked document in the same frame as it was clicked (this is default)._parent
: Opens the linked document in the parent frameset._top
: Opens the linked document in the full body of the window.framename
: Opens the linked document in a named frame.
title
optional
Text that will display on hover of the anchor.
Note: This does not create a popover.
Alias of addLink
.
Creates the same result as addLink
, except the result is wrapped in <p>
tags.
See addLink
.
Alias of addParaLink
.
level
An integer ranging from 1 to 6.
Any value below 1 is treated as 1, and any value above 6 is treated as 6. Additionally, any value that is not an integer is treated as 1.str
The content of the heading.classes
optional
Any extra classes to apply to the anchor, such ash3
.
Alias of addHeading
.
None.
Render will return an HTMLElement instance.
You might be thinking "Why has this guy created this? Do we actually need this?".
To be honest, I'm not sure we actually need it. I am a fledgling programmer and made this because it was something that I thought that I needed for my projects.
I was working in AngularJS and performing AJAX operations, I needed some way to notify the user of what had happened.
A typical example of work might be.
let ba = new BootstrapAlert({ dismissible: true });
$http.post('/path/to/api', { 'username': 'somePersonToInsert' })
.then(function(response) {
if (response.data.success) {
ba.setBackground('success');
ba.addP('<b>Success!</b> That user was added successfully.');
} else if (response.data.failed) {
ba.setBackground('danger');
ba.addP('<b>Failed!</b> That user was not added successfully.');
}
}, function(response) {
ba.setBackground('danger');
ba.addP('<b>Failed!</b> Something unexpected happened.');
})
.then(function() {
$(ba.render()).insertBefore($('#my-form'));
});
In the above example, data was sent to the server and then a Bootstrap alert was created to reflect the success of this action, before being inserted before the form.