Create an alert which the user can close

Description: Show a warning alert with a close button. When the user clicks the button, the alert must disappear.

Hint:

  • Use alert-dismissible fade show, btn-close and data-bs-dismiss="alert".

Solution

<div class="alert alert-warning alert-dismissible fade show" role="alert" id="al">
  <strong>Careful!</strong> Your session will end in 5 minutes.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
Live preview

console.log('alert before: ' + document.querySelectorAll('#al').length);
document.querySelector('#al .btn-close').click();
await new Promise(r => setTimeout(r, 600));
console.log('alert after the click: ' + document.querySelectorAll('#al').length);
Console output (real Chrome)

alert before: 1
alert after the click: 0

How it works

  • data-bs-dismiss="alert" tells Bootstrap to close the alert, and fade show gives the smooth effect.

Read Alerts.


Learn more about the similar topics:
Tutorials
Bootstrap Buttons
Bootstrap Alerts
Bootstrap Badges
Bootstrap Cards
Bootstrap List Group
Bootstrap Progress Bars and Spinners
Bootstrap Icons
Exercises & Assignments
Create a card with an image, a title, a text and a button
Create an alert which the user can close
Create a progress bar at 60 percent
Create a pricing section with three cards
Create a button group
Add a notification count badge to a button
Create a hero section with a heading and two buttons
Interview Questions & Answers
How do you create buttons in Bootstrap?
How do you make a full width button in Bootstrap 5?
What are Bootstrap alerts and how do you close them?
What is a card in Bootstrap?
How do you use Bootstrap Icons?
How do you make cards of equal height in Bootstrap?