You can use the Bootstrap methods to achieve this. Take a look here at the bottom of the page for more info.
Logic
When the button is clicked jQuery removes the class d-none
of the alert element which makes it visible. And then by using setTimeout()
JS will wait 2000ms before closing the alert with alert()
bootstrap 4 method.
It will work for only one click.
Note: using Bootstrap 4 methods requires to work with jQuery.
$('#btn').click(function(){
$('#alert').removeClass('d-none');
setTimeout(() => {
$('.alert').alert('close');
}, 2000);
})
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous">
<div id="alert" class="alert alert-primary m-3 d-none" role="alert">
This is a primary alert—check it out!
</div>
<button class="btn btn-primary m-3" id="btn">
show alert and close it in 2 seconds
</button>
With plain JavaScript
This code will show the alert every time the user clicks the button. In case you don't want that, you could use a Boolean or a session storage variable combined with a conditional statement to make it work only once.
const btn = document.getElementById('btn'),
alert = document.getElementById('alert');
btn.addEventListener('click', () => {
alert.classList.remove('d-none');
setTimeout(() => {
alert.classList.add('d-none');
}, 2000)
})
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous">
<div id="alert" class="alert alert-primary m-3 d-none" role="alert">
This is a primary alert—check it out!
</div>
<button id="btn" class="btn btn-primary m-3">
show alert and close it in 2 seconds
</button>