GoranStimac.com



How To Add Bootstrap 5 Toast on Page Load

Push notifications to your visitors with a toast, a lightweight and easily customizable alert message.

Toasts are lightweight notifications designed to mimic the push notifications that have been popularized by mobile and desktop operating systems. They’re built with flexbox, so they’re easy to align and position.

Things to know when using the toast plugin:

  • Toasts are opt-in for performance reasons, so you must initialize them yourself.
  • Toasts will automatically hide if you do not specify autohide: false.

Basic HTML code from Bootstrap docks:

<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

Basic JS code from my head needed for toast load:

window.onload = (event) => {
    let myAlert = document.querySelectorAll('.toast');
    let bsAlert = new bootstrap.Toast(myAlert);
    bsAlert.show();
}

Find more in official Bootstrap 5 documentation.

Related Posts