Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 665
tibbe Avatar asked Jan 22 '12 21:01

tibbe


People also ask

Can I CSS an alert?

The standard alert box in JavaScript does not provide the option to apply CSS. To style your alert box, you need to create a custom one first. The custom alert box will be created using jQuery and styles will be applied to CSS.

How do I make bootstrap alerts automatically disappear?

To close the alert message, add a . alert-dismissible class to the alert container. Then add class="close" and data-dismiss="alert" to a link or a button element (when you click on this the alert box will disappear).


1 Answers

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(); 
like image 94
Sanjay Avatar answered Sep 16 '22 14:09

Sanjay