Bootstrap 5 Alerts: Dismissible and Dynamic Alert Messages

Alerts are the colored boxes that tell a user something just happened: a message was sent, a save failed, a connection dropped. In Bootstrap 5.3 the markup is still a div with two classes, but the close button changed completely and jQuery is no longer involved.

Page setup

The alert styles are CSS. The close button needs the JavaScript bundle.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap alerts</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <main class="container py-4">
    <!-- alerts go here -->
  </main>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Dismissible alerts

<div class="alert alert-success alert-dismissible fade show" role="alert">
  <strong>Success.</strong> Your message has been sent.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <strong>Warning.</strong> There was a problem with your network connection.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

<div id="myAlert" class="alert alert-info alert-dismissible fade show" role="alert">
  <strong>Note.</strong> Please read the comments carefully.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

<div class="alert alert-danger alert-dismissible fade show" role="alert">
  <strong>Error.</strong> A problem occurred while submitting your data.
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

Each class has a job:

  • .alert-dismissible adds padding on the right so the text does not run under the close button.
  • .fade and .show make the alert fade out when it is closed instead of disappearing at once.
  • role="alert" makes screen readers announce the message.
  • aria-label="Close" gives the button a name, since it has no visible text.

There are also .alert-primary, .alert-secondary, .alert-light and .alert-dark variants.

What changed from Bootstrap 3

The close control used to be <a href="#" class="close" data-dismiss="alert">&times;</a>. In Bootstrap 5, .close is replaced by .btn-close, an empty <button> that draws its own X as a background image, and data-dismiss became data-bs-dismiss. Copying the old markup into a Bootstrap 5 page gives you an unstyled “×” link that does nothing.

It should also be a real <button>. A link with href="#" jumps to the top of the page if the script has not loaded yet, and it is announced as a link rather than a button.

Showing alerts from JavaScript

Most alerts in a real application are created in response to something, such as an API call that failed. Keep an empty container on the page and add alerts to it:

<div id="alert-placeholder"></div>
function showAlert(message, type = 'success') {
  const wrapper = document.createElement('div');
  wrapper.innerHTML = `
    <div class="alert alert-${type} alert-dismissible fade show" role="alert">
      <div class="alert-message"></div>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>`;

  const alert = wrapper.firstElementChild;
  alert.querySelector('.alert-message').textContent = message;
  document.getElementById('alert-placeholder').append(alert);
  return alert;
}

showAlert('Your settings were saved.');

The message is set with textContent, not pasted into the HTML string. If the text ever contains something a user typed, such as a file name, building it into innerHTML would let them inject markup into the page.

The close button works on alerts added this way without any extra code, because Bootstrap listens for data-bs-dismiss clicks on the whole document.

To close an alert from code, for example after five seconds:

const alert = showAlert('Saved.');

setTimeout(() => {
  if (alert.isConnected) {
    bootstrap.Alert.getOrCreateInstance(alert).close();
  }
}, 5000);

The isConnected check skips alerts the user has already closed. Use auto-closing alerts with care: someone using a screen reader or reading slowly may not finish the message in five seconds. Errors in particular should stay until they are dismissed.

close() removes the element from the page. If you want to show the same alert again later, hide it with a utility class instead of closing it. Bootstrap fires closed.bs.alert on the element once it has been removed, which is the place to move keyboard focus somewhere sensible.

Flash messages in ASP.NET Core

A common pattern is to show a success alert after a form post and redirect. Store the message in TempData before the redirect:

TempData["Success"] = "Your message has been sent.";
return RedirectToAction(nameof(Index));

and render it in the layout:

@if (TempData["Success"] is string message)
{
  <div class="alert alert-success alert-dismissible fade show" role="alert">
    @message
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
}

Razor HTML-encodes @message, so the same injection problem as above does not arise here. TempData values are removed once they are read, so the alert shows on exactly one page.

Related examples

1 thought on “Bootstrap 5 Alerts: Dismissible and Dynamic Alert Messages”

  1. I see. This is a really good example. I will share it to my colleague who’s just starting his website. On a side note, just want to ask, Turgay. Do you have some optional close icon for the alert messages? Looking forward to your response. Thanks a lot!

    Reply

Leave a Comment