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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.