Bootstrap Toasts

A toast is a small message in a corner of the screen, like “Saved” or “New message”. It shows for some seconds and then goes away. Toasts are opt-in: you must show them with JavaScript.

A basic toast

<button type="button" class="btn btn-primary" id="liveToastBtn">Show the toast</button>

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <strong class="me-auto">MySite</strong>
      <small>just now</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">Your changes are saved.</div>
  </div>
</div>
<script>
  document.getElementById('liveToastBtn').addEventListener('click', function () {
    bootstrap.Toast.getOrCreateInstance(document.getElementById('liveToast')).show();
  });
</script>
Live preview

const toastEl = document.getElementById('liveToast');
console.log('visible at the start: ' + toastEl.classList.contains('show'));
document.getElementById('liveToastBtn').click();
await new Promise(r => setTimeout(r, 500));
console.log('visible after the button click: ' + toastEl.classList.contains('show'));
console.log('message: ' + toastEl.querySelector('.toast-body').textContent);
Console output (real Chrome)

visible at the start: false
visible after the button click: true
message: Your changes are saved.

Parts of a toast

  • .toast-container places toasts together. Use position-fixed and position classes like bottom-0 end-0 to put it in a corner.
  • .toast is one message, with .toast-header and .toast-body.
  • role="alert" and aria-live tell screen readers to read the message.

Options

OptionMeaning
autohideThe toast hides by itself (default true)
delayTime in milliseconds before it hides (default 5000)
animationFade effect (default true)
const toast = new bootstrap.Toast(document.getElementById('liveToast'), {
  autohide: true,
  delay: 3000
});
toast.show();

Colored toast

<div class="toast align-items-center text-bg-success border-0 show" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">Saved successfully!</div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>
Live preview

Note: Use a toast for a short and not critical message. For an important error use an alert, because a toast can disappear before the user reads it. Next: Progress and Spinners.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.