All of the above solutions use external libraries, either angular or jQuery, and an old version of Bootstrap. So, here is Charles Wyke-Smith's solution in pure JavaScript, applied to Bootstrap 4. Yes, Bootstrap requires jQuery for its own modal and alerts code, but not everyone writes their own code with jQuery any more.
Here is the html of the alert:
<div id="myAlert" style="display: none;"
class="alert alert-success alert-dismissible fade show">
<button type="button" class="close" data-hide="alert">×</button>
<strong>Success!</strong> You did it!
</div>
Note that initially the alert is hidden (style="display: none;"
), and instead of the standard data-dismiss="alert"
, we have here used data-hide="alert"
.
Here is the JavaScript to show the alert and override the close button:
var myAlert = document.getElementById('myAlert');
// Show the alert box
myAlert.style.display = 'block';
// Override Bootstrap's standard close action
myAlert.querySelector('button[data-hide]').addEventListener('click', function() {
myAlert.style.display = 'none';
});
If you wish to hide or show the alert programmatically elsewhere in the code, just do myAlert.style.display = 'none';
or myAlert.style.display = 'block';
.