Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Automatically Close Alerts using Twitter Bootstrap

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?
like image 627
Mario Zigliotto Avatar asked Oct 04 '11 04:10

Mario Zigliotto


People also ask

How do I stop bootstrap alerts automatically?

Closing Alerts To close the alert message, add a . alert-dismissible class to the alert container. Then add class="close" and data-dismiss="alert" to a link or a button element (when you click on this the alert box will disappear).

How do I turn off alerts after some time?

Basic idea is to use jQuery setTimeout() method to close the alert after specified time. Note: Delay is defined in milliseconds. 1 second is equal to 1000 milliseconds. Example 1: In this example, alert is accessed in script using the id and then alert is closed after 5 seconds.

Which bootstrap 4 class can be used to create successful alert?

Bootstrap 4 provides an easy way to create predefined alert messages. Alerts are created with the . alert class, followed by one of the eight contextual classes .


1 Answers

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.

like image 60
jessegavin Avatar answered Oct 23 '22 18:10

jessegavin