Dynamically creating Bootstrap CSS alert messages

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.