bhylu.com

Advertisements

Bootstrap 5 Dismissible Alerts

Observe the close lifecycle without removing an essential instruction from the only place it appears.

How it works

A dismissible Bootstrap alert requires its JavaScript plugin, not only a close-button class. The close control needs an accessible name and the alert content should be genuinely optional after dismissal. The plugin emits lifecycle events and removes the alert element when closed. If focus was inside removed content, the application may need a deliberate next focus target. This example begins with a persistent instruction, then provides a separate dismissible practice note.

Run and inspect

Save the complete document as index.html in a separate lab folder. Place Bootstrap 5.3.8 CSS and the matching JavaScript bundle beside it. Open the file in a normal browser. A separate local static server is optional; no database or PHP execution is required. Keep the Bootstrap licence and bundled Popper licence with redistributed assets.

Download this complete HTML source.

This example needs the complete local setup with the Bootstrap JavaScript bundle. The restricted CSS playground does not reproduce this example’s full contract.

Example

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap 5 Dismiss a Supplemental Alert Through Its Plugin</title>
  <link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<main class="container py-4">
  <h1 class="h3 mb-4">Repair day</h1>
<p>Arrival remains at 09:30 through the east entrance.</p><div id="practice-alert" class="alert alert-info alert-dismissible"><p class="mb-0">Optional practice note: spare sample sheets are available.</p><button id="dismiss-note" class="btn-close" type="button" data-bs-dismiss="alert" aria-label="Dismiss optional practice note"></button></div><p id="alert-state" class="mb-0" role="status">Note visible.</p>
</main>
  <script src="bootstrap.bundle.min.js"></script>
  <script>
document.querySelector("#practice-alert").addEventListener("closed.bs.alert", () => { document.querySelector("#alert-state").textContent = "Optional note closed."; });
  </script>
</body>
</html>

Expected result

Closing the optional note removes that alert and announces its closed state, while arrival instructions remain visible.

The closed event gives the application a reliable point to update its own status. Manually removing markup would bypass the component’s transition and lifecycle contract. The example does not rely on the note for essential event requirements, so dismissal does not make the remaining page unusable. A real focus policy should consider where the close button’s focus goes after removal.

Check Bootstrap’s official 5.3 documentation for component contracts and version details.