Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  87] [ 6]  / answers: 1 / hits: 100711  / 13 Years ago, sun, january 22, 2012, 12:00:00

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?


More From » jquery

 Answers
9

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();

[#87864] Friday, January 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesse

Total Points: 513
Total Questions: 118
Total Answers: 106

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;