d4rty
d4rty

Reputation: 4178

Show an bootstrap alert several times from JS

<div id="alertError" class="alert alert-danger">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        <div id="alertErrorText"></div>
</div>

I want show this alert from several locations in my code. So far I open the alert with the code below, but this solution works only once. After the user closed the alert, the next time the code below is executed, the alert will not be shown.

$("#alertErrorText").html('error');
$("#alertError").fadeIn("slow");

How can I fix this issue?

Upvotes: 1

Views: 88

Answers (2)

T J
T J

Reputation: 43156

The data-dismiss="alert" is causing the element to be removed from DOM itself. You should remove it and write your own handler to simply hide the alert, something like:

$('.alert .close').on('click',function(){
  $(this).closest('.alert').hide();
});

$("#alertErrorText").html('error');
$("#alertError").fadeIn("slow");
<div id="alertError" class="alert alert-danger">
  <a href="#" class="close" aria-label="close">&times;</a>
  <div id="alertErrorText"></div>
</div>

Demo

Upvotes: 2

Nico_
Nico_

Reputation: 1386

According to Bootstrap's documentation :

$().alert('close')

"Closes an alert by removing it from the DOM. If the .fade and .in classes are present on the element, the alert will fade out before it is removed."

So it's normal, you can't reuse it. But you can bind your code on the close event and fade the alert out.

$('#alertError').on('close.bs.alert', function (event) {
    //your code to fade out the element and prevent default comportement.
})

Upvotes: 1

Related Questions