
Bs5 Toast in Bootstrap
Sure! Here’s a handy guide on Bootstrap 5 Toasts — small, dismissible notification popups.
? Bootstrap 5 Toasts
Toasts are lightweight notifications designed to mimic the push notifications on mobile and desktop.
1. Basic Toast Markup
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <strong class="me-auto">Bootstrap</strong> <small class="text-muted">just now</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>
2. Toast Container
Usually, you wrap toasts in a container positioned on the page:
<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 11;"> <!-- Toast(s) here --></div>
3. Show Toast with JavaScript
To show a toast, use Bootstrap’s JS API:
var toastEl = document.querySelector('.toast');var toast = new bootstrap.Toast(toastEl);toast.show();
4. Autohide & Delay
By default, toasts auto-hide after 5 seconds. Customize with options:
var toast = new bootstrap.Toast(toastEl, { delay: 3000, // 3 seconds autohide: true // default is true});toast.show();
To disable autohide:
var toast = new bootstrap.Toast(toastEl, { autohide: false });toast.show();
5. Placement Utilities
Bootstrap 5 offers various classes for toast placement:
.top-0
,.bottom-0
.start-0
,.end-0
.top-50
,.bottom-50
,.start-50
,.end-50
Example container class:
<div class="toast-container position-fixed top-0 end-0 p-3"> <!-- toasts here --></div>
6. Example: Full Toast with Show Button
<button id="liveToastBtn" class="btn btn-primary">Show Toast</button><div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 11;"> <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <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, this is a toast message. </div> </div></div><script> var toastTrigger = document.getElementById('liveToastBtn'); var toastElement = document.getElementById('liveToast'); var toast = new bootstrap.Toast(toastElement); toastTrigger.addEventListener('click', () => { toast.show(); });</script>
Summary
Feature | Usage/Description |
---|---|
.toast | Toast component container |
.toast-header | Header section with title & close button |
.toast-body | Message content |
bootstrap.Toast JS | API to show/hide toasts |
autohide , delay | Options for auto hiding |
.toast-container | Position container for toasts |
Want help building custom toast notifications or integrating them with events? Just ask!