Lesson 32 +10 XP

Toasts

Toasts

Toasts are small notifications that appear in the corner of the screen, similar to push notifications. They need JavaScript to show and dismiss.

Basic toast

<div class="toast show">
  <div class="toast-header">
    <strong class="me-auto">Bootstrap</strong>
    <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

The key classes

  • .toast is the base class.
  • .toast-header holds the title and close button.
  • .toast-body holds the message.
  • .show displays the toast.
  • data-bs-dismiss="toast" closes it.
  • .me-auto pushes the close button to the right.

Showing toasts with JavaScript

Toasts usually start hidden. Use JavaScript to show them:

var toastEl = document.getElementById("myToast");
var toast = new bootstrap.Toast(toastEl);
toast.show();

Toast container

Position toasts with a container and utilities. A common pattern places them in the top right:

<div class="position-fixed top-0 end-0 p-3">
  <div id="myToast" class="toast" role="alert">
    <div class="toast-body">A new message arrived!</div>
  </div>
</div>

Options

  • data-bs-delay sets how long a toast stays visible (in milliseconds).
  • data-bs-autohide controls whether the toast hides itself.

TL;DR

  • Toasts are small notification boxes.
  • .toast + .toast-header + .toast-body build one.
  • Use JavaScript to show and hide them.
  • position-fixed + top-0 + end-0 position them in a corner.