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>');
}
Create 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)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With