Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove bootstrap alert after certain amount of time

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>');
}
like image 207
django Avatar asked May 17 '13 08:05

django


2 Answers

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

like image 158
George Avatar answered Oct 22 '22 07:10

George


try this one

$(function () {

 setTimeout(function () {
            if ($(".alert").is(":visible")){
                 //you may add animate.css class for fancy fadeout
                $(".alert").fadeOut("fast");
            }
        }, 3000)

});
like image 44
danny Avatar answered Oct 22 '22 07:10

danny