I am using dynamic bootstrap alerts from an example. See below.
How can I add a timeout function so alert closes automatically after X time ?
HTML:
<div id="alert_placeholder"></div>
JQUERY:
bootstrap_alert = function() {
}
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').append('<div class="alert alert-block fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4>Info!</h4>'+ message +'</div>');
}
bootstrap_alert.info = function(message) {
$('#alert_placeholder').append('<div class="alert alert-block alert-info fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4>Info!</h4>'+ message +'</div>');
}
I am using dynamic bootstrap alerts from an example. See below.
How can I add a timeout function so alert closes automatically after X time ?
HTML:
<div id="alert_placeholder"></div>
JQUERY:
bootstrap_alert = function() {
}
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').append('<div class="alert alert-block fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4>Info!</h4>'+ message +'</div>');
}
bootstrap_alert.info = function(message) {
$('#alert_placeholder').append('<div class="alert alert-block alert-info fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4>Info!</h4>'+ message +'</div>');
}
Share
Improve this question
edited May 17, 2013 at 8:54
George
36.8k9 gold badges69 silver badges109 bronze badges
asked May 17, 2013 at 8:12
djangodjango
2,9096 gold badges50 silver badges83 bronze badges
2 Answers
Reset to default 11Create a function that removes the first (hence, oldest) alert:
function alertTimeout(wait){
setTimeout(function(){
$('#alert_placeholder').children('.alert:first-child').remove();
}, wait);
}
[0]
to ensure that only the first alert gets removed, for each timeout.
And then call the function when you show the alert, with the parameter being how long until the alert closes, in milliseconds:
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').append('<div class="alert alert-block fade in"><button type="button" class="close" data-dismiss="alert">×</button><h4>Info!</h4>'+ message +'</div>');
alertTimeout(5000);
}
Please see this jsFiddle
try this one
$(function () {
setTimeout(function () {
if ($(".alert").is(":visible")){
//you may add animate.css class for fancy fadeout
$(".alert").fadeOut("fast");
}
}, 3000)
});