I am in the process of developing an alert system for a web application using Bootstrap 4. Below is the code I have implemented:
function bsalert(str1, str2) {
$(".alert").addClass('show');
$(".alert").addClass('alert-'+str1);
$('.alert').html(str2);
setTimeout( function() {
$(".alert").removeClass('show');
$(".alert").removeClass('alert-'+str1);
}, 2000 );
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div class="alert alert-dismissible fade text-center" role="alert" id="alert"></div>
<button type="button" class="btn btn-outline-primary" onclick="bsalert('danger', 'ALERT!');">one</button>
<button type="button" class="btn btn-outline-primary" onclick="bsalert('success', 'nice');">two</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9c839c9c899ec2869facddc2dddac2dc">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
The challenge I'm encountering is that if the alert is triggered too rapidly before the timer removes the class, it disrupts the ability to change the alert types. How can this issue be resolved? Is there a more efficient built-in function in Bootstrap that can handle this?
Edit: Although this example showcases a simplified version with only danger
and success
alert types, in reality, there are more variations available.