Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade out multiple Bootstrap alerts

I came across a question asking how to fade out Bootstrap alerts after 5 seconds, and the answer was the following code. The issue is, it only works once, however as I have multiple alerts that are generated after an AJAX call this is no good. How do I make the following code run every time an alert is triggered?

window.setTimeout(function() {
     $(".alert").fadeTo(500, 0).slideUp(500, function(){
          $(this).remove(); 
     });
}, 5000);
like image 359
Benedict Lewis Avatar asked Apr 23 '26 17:04

Benedict Lewis


1 Answers

One possible solution is to use a custom event showalert after the alert is shown and in the event handler remove the alert

$(document).on('showalert', '.alert', function(){
    window.setTimeout($.proxy(function() {
        $(this).fadeTo(500, 0).slideUp(500, function(){
            $(this).remove(); 
        });
    }, this), 5000);
})  

and

$('<div class="alert alert-error">' + 'some message' + '</div>').appendTo('#result').trigger('showalert');

Demo: Fiddle

like image 194
Arun P Johny Avatar answered Apr 26 '26 05:04

Arun P Johny