91

I'm using twitter's bootstrap CSS framework (which is fantastic). For some messages to users I am displaying them using the alerts Javascript JS and CSS.

For those interested, it can be found here: http://getbootstrap.com/javascript/#alerts

My issue is this; after I've displayed an alert to a user I'd like it to just go away after some time interval. Based on twitter's docs and the code I've looked through it looks like this is not baked in:

  • My first question is a request for confirmation that this is indeed NOT baked into Bootstrap
  • Secondly, how can I achieve this behavior?
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Mario Zigliotto
  • 8,315
  • 7
  • 52
  • 71
  • Take a look here http://stackoverflow.com/questions/23101966/bootstrap-alert-auto-close#answer-23102317 that's the best answer I found – Andres Oct 07 '14 at 19:46

10 Answers10

109

Calling window.setTimeout(function, delay) will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

If you want to wrap it in a nifty function you could do this.

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

Then you could use it like so...

createAutoClosingAlert(".alert-message", 2000);

I am certain there are more elegant ways to accomplish this.

jessegavin
  • 74,067
  • 28
  • 136
  • 164
  • Hey jesse thank you! the setTimeout works and i'll select it as a valid solution, but it appears the behavior should in fact be baked in as TK Kocheran stated (and logged). – Mario Zigliotto Oct 04 '11 at 05:22
  • I looked at the twitter bootstrap code and didn't see any support for auto-closing alerts. – jessegavin Oct 04 '11 at 05:30
  • Yes -- im waiting on TK's response because from his message here it sounds like the auto-close functionality should be there and is not -- but the bug report on github makes no reference to that. – Mario Zigliotto Oct 04 '11 at 05:31
  • Yeah they're not claiming to be able to auto close alerts, only to be able t programmatically close them with the provided jQuery plugin. ie `$('#myAlert').alert('close')` doesn't work as advertised. – Naftuli Kay Oct 04 '11 at 07:47
  • You may want to extend jQuery and dispatch that method off the object, like: `$('#my_fancy_alert').createAutoClosingAlert(2000)`. You just need to pass `$(this).remove()` or `$(this).alert('close')` in `setTimeout` callback. – aL3xa Sep 13 '12 at 22:35
  • Thanks! This works really well! TIP: if you want to achieve a nice transition with pretty much no extra work, you can add the classes "fade in" to the alert widget. – Darío Javier Cravero Jan 06 '13 at 02:53
  • Instead all this there should be a property like "auto-hide". aaah – Shahid Karimi Jan 31 '13 at 22:08
  • For those having trouble with the `alert('close')`, try setting `data-target=` on the alert holder div – James McMahon Apr 21 '13 at 21:49
  • Looking around for the solution, maybe we can use this : http://nijikokun.github.io/bootstrap-notify/ – swdev Oct 01 '13 at 10:32
  • Can confirm this works with bootstrap 4 alerts. All you need to do is change `".alert-message"` to `".alert"` for the first example and it works perfectly. – Jake Apr 04 '19 at 12:44
99

I could not get it to work with alert.('close') either.

However I am using this and it works a treat! The alert will fade away after 5 seconds, and once gone, the content below it will slide up to its natural position.

window.setTimeout(function() {
    $(".alert-message").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);
moogboy
  • 991
  • 5
  • 2
  • Definitely a great solution. The alert fades out really nicely after the short interval. Looks very professional. – Matthew Setter Jun 29 '13 at 18:57
  • Working fast and great indeed. – Mohamed Anis Dahmani Jan 19 '14 at 23:47
  • 1
    Does this have to be called each time the alert is displayed, or does it work automatically for all alerts with class `.alert-message`? Having trouble, the class on my BS3 alert is `alert alert-danger alert-block`, so should I use `.alert`, `alert-danger`, or the full class name in the timeout function? – raffian Jan 25 '14 at 15:41
  • @raffian Put it like this: `$(".alert-message,.alert-danger,.alert-info")` and so on. You have to figure out whether you want it in your entire website or not. If you want it in every page, for example, in Laravel's blade you can use something like @include('scripts-alerts') or @yield('alerts'). You have to figure out or ask a specific question in stackoverflow and not here... – Pathros May 20 '15 at 17:22
  • Yeah, this is a nice one! Worked great for me, and is a small amount of code +1. – edencorbin Aug 26 '15 at 02:07
  • 1
    The best way to do this. Should be marked as the correct answer @Mario Zigliotto since other elements slide up slowly and do not change their position immediately. That looks far more beautiful and professional. – Torsten Barthel Feb 23 '16 at 02:54
  • This works with Bootstrap 4, and you can make it by changing `".alert-message"` to `".alert"`. – Jake Apr 04 '19 at 12:46
4

I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.

window.setTimeout(function() { // hide alert message
    $("#alert_message").removeClass('in'); 

}, 5000);

When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)

    $('#Some_Button_Or_Event_Here').click(function () { // Show alert message
        $('#alert_message').addClass('in'); 
    });
3

Using the 'close' action on the alert does not work for me, because it removes the alert from the DOM and I need the alert multiple times (I'm posting data with ajax and I show a message to the user on every post). So I created this function that create the alert every time I need it and then starts a timer to close the created alert. I pass into the function the id of the container to which I want to append the alert, the type of alert ('success', 'danger', etc.) and the message. Here is my code:

function showAlert(containerId, alertType, message) {
    $("#" + containerId).append('<div class="alert alert-' + alertType + '" id="alert' + containerId + '">' + message + '</div>');
    $("#alert" + containerId).alert();
    window.setTimeout(function () { $("#alert" + containerId).alert('close'); }, 2000);
}
Daniele Armanasco
  • 7,289
  • 9
  • 43
  • 55
2

This is the coffescript version:

setTimeout ->
 $(".alert-dismissable").fadeTo(500, 0).slideUp(500, -> $(this.remove()))
,5000
Johniboy
  • 41
  • 3
2

With each of the solutions above I continued to lose re-usability of the alert. My solution was as follows:

On page load

$("#success-alert").hide();

Once the alert needed to be displayed

 $("#success-alert").show();
 window.setTimeout(function () {
     $("#success-alert").slideUp(500, function () {
          $("#success-alert").hide();
      });
 }, 5000);

Note that fadeTo sets the opacity to 0, so the display was none and the opacity was 0 which is why I removed from my solution.

biggles
  • 78
  • 2
  • 9
0

After going over some of the answers here an in another thread, here's what I ended up with:

I created a function named showAlert() that would dynamically add an alert, with an optional type and closeDealy. So that you can, for example, add an alert of type danger (i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:

showAlert("Warning message", "danger", 5000);

To achieve that, add the following Javascript function:

function showAlert(message, type, closeDelay) {

    if ($("#alerts-container").length == 0) {
        // alerts-container does not exist, add it
        $("body")
            .append( $('<div id="alerts-container" style="position: fixed;
                width: 50%; left: 25%; top: 10%;">') );
    }

    // default to alert-info; other options include success, warning, danger
    type = type || "info";    

    // create the alert div
    var alert = $('<div class="alert alert-' + type + ' fade in">')
        .append(
            $('<button type="button" class="close" data-dismiss="alert">')
            .append("&times;")
        )
        .append(message);

    // add the alert div to top of alerts-container, use append() to add to bottom
    $("#alerts-container").prepend(alert);

    // if closeDelay was passed - set a timeout to close the alert
    if (closeDelay)
        window.setTimeout(function() { alert.alert("close") }, closeDelay);     
}
isapir
  • 21,295
  • 13
  • 115
  • 116
0

I needed a very simple solution to hide something after sometime and managed to get this to work:

In angular you can do this:

$timeout(self.hideError,2000);

Here is the function that i call when the timeout has been reached

 self.hideError = function(){
   self.HasError = false;
   self.ErrorMessage = '';
};

So now my dialog/ui can use those properties to hide elements.

leeroya
  • 485
  • 7
  • 12
0

With delay and fade :

setTimeout(function(){
    $(".alert").each(function(index){
        $(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
            $(this).remove();
        });
    });
},2000);
Gigoland
  • 1,287
  • 13
  • 10
0

try this one

$(function () {

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

        }, 3000)

});
danny
  • 407
  • 1
  • 5
  • 10