How to Automatically Close Alerts using Twitter Bootstrap

Mario Zigliotto picture Mario Zigliotto · Oct 4, 2011 · Viewed 142.4k times · Source

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?

Answer

jessegavin picture jessegavin · Oct 4, 2011

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.