Using Bootstrap 5 Toasts for Form Feedback and Notifications

Using Bootstrap 5 Toasts for Form Feedback and Notifications

Bootstrap 5 toast component covers the majority of real-world use cases without adding a single extra dependency, and when you understand how the JavaScript API works, you gain precise control over timing, stacking, and accessibility.

Key Takeaways

  • Bootstrap 5 toasts require explicit initialisation via JavaScript; they are hidden by default and will not appear without it.
  • The Toast JavaScript API exposes show(), hide(), and dispose() methods plus a full event lifecycle you can hook into.
  • Stacked toasts, custom colours, and auto-dismiss delays are all achievable with markup attributes and a small amount of vanilla JS.
  • Accessibility depends on correct ARIA roles: use role="status" for non-critical messages and role="alert" for errors.
  • Keeping toast initialisation lean matters for performance; avoid re-querying the DOM on every trigger.

What a Bootstrap 5 Toast Actually Is

A toast is a lightweight, non-blocking notification that appears at a corner of the viewport, delivers a message, and then disappears after a set delay. Bootstrap 5 ships its own toast component as part of the core package, with no jQuery dependency. The component relies on bootstrap.js (or the individual toast.js module) and vanilla CSS transitions.

The key difference from a modal or alert is that a toast does not interrupt the user’s workflow. It is ideal for confirming background actions: a form submitted, a cart updated, a file uploaded. Where a modal demands attention, a toast merely informs.

One thing to state clearly upfront: Bootstrap 5 toasts are opt-in. Drop the markup into a page without wiring up JavaScript and nothing will appear. The component is hidden by default and must be initialised and triggered explicitly.

Using Bootstrap 5 Toasts for Form Feedback and Notifications, abstract concept illustration

Basic Toast Markup

The minimum viable toast has a wrapper element, an optional header, and a body. Place toast wrappers inside a positioning container near the end of the <body>.

<!-- Positioning container -->
<div
  aria-live="polite"
  aria-atomic="true"
  class="position-fixed bottom-0 end-0 p-3"
  style="z-index: 1100"
>
  <!-- Individual toast -->
  <div
    id="liveToast"
    class="toast"
    role="status"
    aria-live="polite"
    aria-atomic="true"
    data-bs-delay="4000"
  >
    <div class="toast-header">
      <strong class="me-auto">Notification</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 form has been submitted successfully.
    </div>
  </div>
</div>

The data-bs-delay attribute accepts milliseconds. The default is 5000 ms. Setting data-bs-autohide="false" keeps the toast visible until the user dismisses it manually, which is appropriate for error messages that demand action.

Initialising Toasts with the JavaScript API

Bootstrap 5’s Toast JavaScript API is straightforward. Instantiate a Toast object from any element carrying the .toast class, then call .show().

<script>
// Cache the element once
const toastEl = document.getElementById('liveToast');
const toast = new bootstrap.Toast(toastEl, {
  delay: 4000,
  autohide: true,
  animation: true
});

// Trigger from a form submit handler
document.getElementById('contactForm').addEventListener('submit', function (e) {
  e.preventDefault();
  // ... your form processing logic ...
  toast.show();
});
</script>

The constructor accepts an options object that mirrors the data attributes. Options passed in JavaScript take precedence over markup attributes, which is useful when you want to vary the delay programmatically based on message severity.

Available methods:

  • toast.show() reveals the component and starts the auto-dismiss timer.
  • toast.hide() programmatically dismisses the toast before the timer expires.
  • toast.dispose() destroys the instance and frees memory. Call this when removing toast elements from the DOM dynamically.
  • bootstrap.Toast.getInstance(element) returns an existing instance so you avoid creating duplicates.

Available events:

  • show.bs.toast fires immediately when .show() is called.
  • shown.bs.toast fires after the CSS transition completes.
  • hide.bs.toast fires when hiding begins.
  • hidden.bs.toast fires after the element is fully hidden. This is the right moment to update message text before the next call to .show().
notification component html, abstract technical diagram

Practical Pattern: Form Feedback with Dynamic Messages

A single reusable toast element that accepts dynamic content is more efficient than maintaining separate markup for every possible message. The pattern below swaps the body text inside the hidden.bs.toast event, so content is only updated after the previous notification has fully disappeared.

<div id="formToast" class="toast align-items-center border-0" role="status" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body" id="formToastMessage"></div>
    <button
      type="button"
      class="btn-close btn-close-white me-2 m-auto"
      data-bs-dismiss="toast"
      aria-label="Close"
    ></button>
  </div>
</div>

<script>
const toastEl = document.getElementById('formToast');
const toastBody = document.getElementById('formToastMessage');
const toast = new bootstrap.Toast(toastEl, { delay: 5000 });

function showToast(message, type = 'success') {
  const colours = {
    success: 'bg-success text-white',
    error: 'bg-danger text-white',
    info: 'bg-primary text-white'
  };
  // Remove any previous colour classes
  toastEl.classList.remove('bg-success', 'bg-danger', 'bg-primary', 'text-white');
  toastEl.classList.add(...colours[type].split(' '));
  toastBody.textContent = message;
  toast.show();
}

// Example: call from fetch callback
document.getElementById('signupForm').addEventListener('submit', async function (e) {
  e.preventDefault();
  try {
    const res = await fetch('/api/signup', {
      method: 'POST',
      body: new FormData(this)
    });
    if (res.ok) {
      showToast('Account created. Check your inbox.', 'success');
    } else {
      showToast('Signup failed. Please try again.', 'error');
    }
  } catch {
    showToast('Network error. Check your connection.', 'error');
  }
});
</script>

This pattern maps well to how the Canvas HTML Template structures its component pages: a single initialisation block, helper functions, and data-driven rendering rather than duplicated markup throughout the file.

Stacking Multiple Toasts

Bootstrap 5 supports stacked toasts natively. Place multiple toast elements inside the same positioning container and the browser stacks them vertically, with each managing its own lifecycle independently.

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="toast1" class="toast" role="status" data-bs-delay="4000">
    <div class="toast-body">First notification</div>
  </div>
  <div id="toast2" class="toast" role="status" data-bs-delay="6000">
    <div class="toast-body">Second notification</div>
  </div>
</div>

For dynamically generated notifications (a real-time dashboard, for example), create new toast elements via JavaScript, append them to the container, show them, then remove them from the DOM inside the hidden.bs.toast event. Call toast.dispose() before removing the node to prevent memory leaks. This keeps the DOM clean regardless of notification volume.

If your project also uses scroll-driven animations, be aware that a large number of simultaneously visible toasts can trigger layout recalculations. The performance considerations discussed in Bootstrap 5 Performance: A Complete Guide to Fast-Loading Templates apply here: batch DOM writes and avoid triggering reflows inside animation frames.

Accessibility for Toast Notifications

The ARIA role you choose communicates urgency to assistive technologies.

  • Use role="status" and aria-live="polite" for confirmations such as “Saved” or “Email sent.” Screen readers announce the content after the user finishes their current task.
  • Use role="alert" and aria-live="assertive" for errors or warnings that require immediate attention. Screen readers interrupt the current announcement.
  • Always pair aria-live with aria-atomic="true" so the entire toast content is read as a single unit rather than piecemeal as it animates in.
  • Provide a visible dismiss button with a meaningful aria-label so keyboard users can close the notification without waiting for auto-dismiss.

If you are building a style guide for your project, documenting these role patterns alongside the component markup is good practice. The workflow described in Creating a Living Style Guide Page for Your HTML Template shows how to capture these decisions in a reusable reference page.

Theming Toasts to Match Your Brand

Bootstrap 5 toasts inherit from the framework’s colour utilities, but you can override defaults with CSS custom properties. Canvas uses the variable --cnvs-themecolor throughout its component system, and you can tie toast colours to the same token:

<style>
.toast-branded {
  background-color: var(--cnvs-themecolor, #0d6efd);
  color: #fff;
  border: none;
}

.toast-branded .btn-close {
  filter: invert(1);
}
</style>

<div id="brandedToast" class="toast toast-branded" role="status" data-bs-delay="4000">
  <div class="d-flex align-items-center p-3">
    <div class="toast-body flex-grow-1">Changes saved to your account.</div>
    <button
      type="button"
      class="btn-close ms-auto"
      data-bs-dismiss="toast"
      aria-label="Close"
    ></button>
  </div>
</div>

Because --cnvs-themecolor is set once at the root level, every branded toast across the template updates automatically when you retheme the project, whether for a single client or multiple brands. The multi-brand theming workflow is covered in depth in Theming One HTML Template for Multiple Client Brands with CSS Variables.

Frequently Asked Questions

The most common cause is missing JavaScript initialisation. Bootstrap 5 toasts are hidden by default and require an explicit call to new bootstrap.Toast(element).show(). Verify that bootstrap.js or bootstrap.bundle.js is loaded before your initialisation script, and that your element selector returns a non-null node. Also confirm the element carries the .toast class, not just an ID.

Add data-bs-autohide="false" to the toast element, or pass { autohide: false } as a constructor option in JavaScript. The toast will remain visible until the user clicks the dismiss button or you call toast.hide() programmatically.

Yes. Wrap the toast in a container with the classes position-fixed top-0 start-50 translate-middle-x p-3. The translate-middle-x utility class horizontally centres the container regardless of its width. Set a suitable z-index (Bootstrap uses 1090 for toasts) to ensure the notification appears above other stacked elements.

A Bootstrap 5 alert is a static inline element that occupies document flow and stays visible until explicitly dismissed or removed from the DOM. A toast is a floating, timed notification that appears outside the document flow, auto-dismisses after a delay, and is designed for transient feedback. Use alerts for persistent validation messages directly beside form fields; use toasts for background action confirmations such as a saved record or a sent email.

Yes. Bootstrap 5 removed the jQuery dependency entirely. The Toast component is written in vanilla ES6 JavaScript and works in all modern browsers (Chrome 90 and above, Firefox 88 and above, Safari 14 and above, Edge 90 and above) with no additional libraries required.

Looking for a production-ready Bootstrap 5 HTML template? Browse Canvas Template demos and find the perfect starting point for your next project.

If you’re building with the Canvas HTML Template and want to ship production-ready Bootstrap 5 layouts faster, try Canvas Builder free — the visual builder that exports clean Canvas-ready markup in minutes.

Skip the setup and build it free

Spin up a complete Bootstrap 5 site, blog included, with Canvas Builder. No coding, no cost.

Share:
Canvas Team
Canvas Team

Tutorials and tips for building beautiful Bootstrap 5 websites with the Canvas HTML Template and Canvas Builder.

More from the Canvas Blog