How to Automatically Close Alerts using Twitter Bootstrap
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');
});
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);
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);
}
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.