Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  121] [ 3]  / answers: 1 / hits: 26044  / 11 Years ago, fri, may 17, 2013, 12:00:00

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>&times;</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>&times;</button><h4>Info!</h4>'+ message +'</div>');
}

More From » jquery

 Answers
10

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>&times;</button><h4>Info!</h4>'+ message +'</div>');
alertTimeout(5000);
}


Please see this jsFiddle


[#78169] Thursday, May 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;