Dynamically create Bootstrap alerts box through JavaScript

JavascriptTwitter Bootstrap

Javascript Problem Overview


I'm using Bootstrap 2.0 for my project and I would like to dynamically add Bootstrap alert box in my page (http://twitter.github.com/bootstrap/javascript.html#alerts). I want to do something like:

bootstrap-alert.warning("Invalid Credentials"); 

Javascript Solutions


Solution 1 - Javascript

Try this (see a working example of this code in jsfiddle: http://jsfiddle.net/periklis/7ATLS/1/)

<input type = "button" id = "clickme" value="Click me!"/>
<div id = "alert_placeholder"></div>
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
            $('#alert_placeholder').html('<div class="alert"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
        }
    
$('#clickme').on('click', function() {
            bootstrap_alert.warning('Your text goes here');
});
</script>

EDIT: There are now libraries that simplify and streamline this process, such as bootbox.js

Solution 2 - Javascript

/**
  Bootstrap Alerts -
  Function Name - showalert()
  Inputs - message,alerttype
  Example - showalert("Invalid Login","alert-error")
  Types of alerts -- "alert-error","alert-success","alert-info","alert-warning"
  Required - You only need to add a alert_placeholder div in your html page wherever you want to display these alerts "<div id="alert_placeholder"></div>"
  Written On - 14-Jun-2013
**/

  function showalert(message,alerttype) {

    $('#alert_placeholder').append('<div id="alertdiv" class="alert ' +  alerttype + '"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')

    setTimeout(function() { // this will automatically close the alert and remove this if the users doesnt close it in 5 secs


      $("#alertdiv").remove();

    }, 5000);
  }

Solution 3 - Javascript

You can also create a HTML alert template like this:

<div class="alert alert-info" id="alert_template" style="display: none;">
    <button type="button" class="close">×</button>
</div>

And so you can do in JavaScript this here:

$("#alert_template button").after('<span>Some text</span>');
$('#alert_template').fadeIn('slow');

Which is in my opinion cleaner and faster. In addition you stick to Twitter Bootstrap standards when calling fadeIn().

To guarantee that this alert template works also with multiple calls (so it doesn't add the new message to the old one), add this here to your JavaScript:

$('#alert_template .close').click(function(e) {
    $("#alert_template span").remove();
});

So this call removes the span element every time you close the alert via the x-button.

Solution 4 - Javascript

I created this VERY SIMPLE and basic plugin:

(function($){
	$.fn.extend({
		bs_alert: function(message, title){
			var cls='alert-danger';
			var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
			if(typeof title!=='undefined' &&  title!==''){
				html+='<h4>'+title+'</h4>';
			}
			html+='<span>'+message+'</span></div>';
			$(this).html(html);
		},
		bs_warning: function(message, title){
			var cls='alert-warning';
			var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
			if(typeof title!=='undefined' &&  title!==''){
				html+='<h4>'+title+'</h4>';
			}
			html+='<span>'+message+'</span></div>';
			$(this).html(html);
		},
		bs_info: function(message, title){
			var cls='alert-info';
			var html='<div class="alert '+cls+' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
			if(typeof title!=='undefined' &&  title!==''){
				html+='<h4>'+title+'</h4>';
			}
			html+='<span>'+message+'</span></div>';
			$(this).html(html);
		}
	});
})(jQuery);

Usage is

<div id="error_container"></div>
<script>
$('#error_container').bs_alert('YOUR ERROR MESSAGE HERE !!', 'title');
</script>

first plugin EVER and it can be easily made better

Solution 5 - Javascript

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

In html:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

In JS:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');
  
  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>

Then you can invoke this either as:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

Solution 6 - Javascript

just recap:

$(document).ready(function() {

    $('button').on( "click", function() {

      showAlert( "OK", "alert-success" );

    } );

});

function showAlert( message, alerttype ) {

    $('#alert_placeholder').append( $('#alert_placeholder').append(
      '<div id="alertdiv" class="alert alert-dismissible fade in ' +  alerttype + '">' +
          '<a class="close" data-dismiss="alert" aria-label="close" >×</a>' +
          '<span>' + message + '</span>' + 
      '</div>' )
    );

    // close it in 3 secs
    setTimeout( function() {
        $("#alertdiv").remove();
    }, 3000 );

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
        
<button onClick="" >Show Alert</button>
      
<div id="alert_placeholder" class="container" ></div>

codepen

Solution 7 - Javascript

FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.

There is a readme there with a more in-depth explanation, but I'll do a quick example below:

var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());

The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".

There are also options that can be set on initialisation.
For your requirement you'd do:

var ba = new BootstrapAlert({
    dismissible: true,
    background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());

The render method will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.

This is a work in progress library, but it still is in a very good working order.

Solution 8 - Javascript

Solution 9 - Javascript

function bootstrap_alert() {
        create = function (message, color) {
            $('#alert_placeholder')
                .html('<div class="alert alert-' + color
                    + '" role="alert"><a class="close" data-dismiss="alert">×</a><span>' + message
                    + '</span></div>');
        };
        warning = function (message) {
            create(message, "warning");
        };
        info = function (message) {
            create(message, "info");
        };
        light = function (message) {
            create(message, "light");
        };
        transparent = function (message) {
            create(message, "transparent");
        };
        return {
            warning: warning,
            info: info,
            light: light,
            transparent: transparent
        };
    }

Solution 10 - Javascript

I found that AlertifyJS is a better alternative and have a Bootstrap theme.

alertify.alert('Alert Title', 'Alert Message!', function(){ alertify.success('Ok'); });

Also have a 4 components: Alert, Confirm, Prompt and Notifier.

Exmaple: JSFiddle

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioned1tView Question on Stackoverflow
Solution 1 - JavascriptperiklisView Answer on Stackoverflow
Solution 2 - JavascriptUberNeoView Answer on Stackoverflow
Solution 3 - JavascriptpvlsgnnksView Answer on Stackoverflow
Solution 4 - JavascriptFabrizioView Answer on Stackoverflow
Solution 5 - JavascriptTedView Answer on Stackoverflow
Solution 6 - JavascriptanteloveView Answer on Stackoverflow
Solution 7 - JavascriptJustCartyView Answer on Stackoverflow
Solution 8 - JavascriptCiremView Answer on Stackoverflow
Solution 9 - Javascriptrom mView Answer on Stackoverflow
Solution 10 - JavascriptAdrian P.View Answer on Stackoverflow