Dynamically creating Bootstrap CSS alert messages

I'm trying to dynamically create alert messages using the jQuery plugin for Bootstrap CSS. I want to create and destroy alerts on certain events (e.g. AJAX success/error). Here's a non-working snippet of my code:

var alertVisible = false;
function fetchData() {
    function onDataReceived(stats) {
        if (alertVisible) {
            $(".alert-message").alert("close");
        }
        alertVisible = false;
        // Do stuff with data...
    }

    function onError() {
        $(".alert-message").alert();
        alertVisible = true;
    }

    $.ajax({
        dataType: 'json',
        success: onDataReceived,
        error: onError,
        cache: false
    });
};

and here's the corresponding HTML:

<div class="row">
  <div class="alert-message error fade in hide span16" data-alert="alert">
    <a class="close" href="#">&times;</a>
    <p>Lost connection to server.</p>
  </div>
</div>

My first problem is that the alert is showed by default. I can kinda solve this by using the hide class. However, if you close an alert (by clicking on the close button) then creating new asserts no longer works (I guess the DOM element is gone). How are you supposed to use Bootstrap alerts?


This answer refers to Bootstrap 2.

When an alert is closed, it is removed from the DOM.

If you want to an alert to reappear later, make sure to not put data-dismiss="alert" in the close button as follows:

<div class="alert fade in" id="login-error" style="display:none;">
    <button type="button" class="close">×</button>
    Your error message goes here...
</div>

Then, bind the close button to simply hide the alert when it's pressed:

$('.alert .close').on('click', function(e) {
    $(this).parent().hide();
});

When you want the tooltip to reappear, simply show it.

$('#login-error').show();

You could just dynamically add the DOM elements for the alert.

Javascript:

function addAlert(message) {
    $('#alerts').append(
        '<div class="alert">' +
            '<button type="button" class="close" data-dismiss="alert">' +
            '&times;</button>' + message + '</div>');
}

function onError() {
    addAlert('Lost connection to server.');
}

HTML:

<div id="alerts"></div>

In the case of multiple alerts, this version will result in multiple alerts piling up that must be individually dismissed by the end user. Depending on how many alerts you expect and how important it is for the user to see each one you might want to modify this to delete old alerts.

Also, with a little refactoring you can extend this to create warning, info, and success alerts in addition to this error alert.


Best way that i know:

HTML:

<div class="alert alert-block alert-error fade in" id="cert-error" style="display:none;">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <h4 class="alert-heading">Этот файл не подходит!</h4>
    <p>Недопустимый тип файла! Выберите файл вида: *.cer, *.crt</p>
    <p>
        <a class="btn btn-danger" href="#">Take this action</a> <a class="btn" href="#">Or do this</a>
    </p>
</div>

JS:

$('.alert .close').live("click", function(e) {
    $(this).parent().hide();
});

function showAlert() {
    $(".alert").addClass("in");
    $("#cert-error").show();
}

function closeAlert() {    
    $("#cert-error").hide();
}

Now we can display notifications using showAlert() and hide them with closeAlert().