How to Automatically Close Alerts using Twitter Bootstrap

JavascriptJqueryCssTwitter BootstrapAlert

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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


					

Solution 4 - Javascript

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

Solution 5 - Javascript

This is the coffescript version:

setTimeout ->
 $(".alert-dismissable").fadeTo(500, 0).slideUp(500, -> $(this.remove()))
,5000

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

With delay and fade :

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

Solution 10 - Javascript

try this one

$(function () {

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

});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMario ZigliottoView Question on Stackoverflow
Solution 1 - JavascriptjessegavinView Answer on Stackoverflow
Solution 2 - JavascriptmoogboyView Answer on Stackoverflow
Solution 3 - JavascriptMark DanielView Answer on Stackoverflow
Solution 4 - JavascriptDaniele ArmanascoView Answer on Stackoverflow
Solution 5 - JavascriptJohniboyView Answer on Stackoverflow
Solution 6 - JavascriptbigglesView Answer on Stackoverflow
Solution 7 - JavascriptisapirView Answer on Stackoverflow
Solution 8 - JavascriptleeroyaView Answer on Stackoverflow
Solution 9 - JavascriptGigolNftView Answer on Stackoverflow
Solution 10 - JavascriptdannyView Answer on Stackoverflow