最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery remove bootstrap alert after certain amount of time - Stack Overflow

programmeradmin1浏览0评论

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>');
}

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>');
}
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
Add a comment  | 

2 Answers 2

Reset to default 11

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

try this one

$(function () {

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

});
发布评论

评论列表(0)

  1. 暂无评论