Bootstrap Toasts

This tutorial will teach you the usage of the Bootstrap toast component


Creating the Toasts with Bootstrap

The newly introduced Bootstrap 4 feature called toasts represents lightweight notifications similar to push notifications on computer screens. Utilizing flexbox, they offer easy alignment and positioning within web pages.

To use toasts, you must opt-in for performance reasons and initialize them manually using the toast() method. By default, toasts will automatically disappear after 5 seconds unless you specify the autohide: false option.

Step 1: Adding the Toast Markup

Creating a toast is straightforward, and you can include a header, body, and close button.

<div class="toast fade show" id="myToast">
<div class="toast-header">
    <strong class="me-auto"><i class="bi-gift-fill"></i> Hai</strong>
    <small>12 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
    How are You <a href="#">Click here!</a>
</div>
</div>

Step 2: Triggering the Toasts

To trigger toasts via JavaScript, simply call the toast() method with the target element's id, class, or CSS selector.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myToast").toast("show");
    });
});
</script>

Changing the Toast's Color Schemes

Customizing toasts is possible by employing color and background utility classes.

For example, you can create a toast with a blue background and white text.

<div class="toast bg-primary text-white fade show">
<div class="toast-header bg-primary text-white">
    <strong class="me-auto"><i class="bi-gift-fill"></i> We miss you!</strong>
    <small>10 mins ago</small>
    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
</div>
<div class="toast-body">
    It's been a long time since you visited us. We've something special for you. <a href="#" class="text-white">Click here!</a>
</div>
</div>

Stacking Toasts Vertically

If you want to stack multiple toasts vertically, wrap them in a toast container for added spacing.

<div class="toast-container">

<div class="toast fade show">
    <div class="toast-header">
        <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
        <small>just now</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body">
        This is a basic toast message.
    </div>
</div>

<div class="toast fade show">
    <div class="toast-header">
        <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
        <small>5 seconds ago</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body">
        See? This is another toast message.
    </div>
</div>
</div>

Placement of Toasts

While you can position toasts anywhere on your web page using custom CSS, it's recommended to place them at the top right, bottom right, or top middle for notifications.

When showing only one toast at a time, it's advisable to put the positioning styles inline on the .toast element.

<div class="toast-container" style="position: absolute; top: 10px; right: 10px;">

    <div class="toast fade show">
        <div class="toast-header">
            <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
            <small>just now</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            This is a basic toast message.
        </div>
    </div>

    <div class="toast fade show">
        <div class="toast-header">
            <strong class="me-auto"><i class="bi-globe"></i> Hello, world!</strong>
            <small>5 seconds ago</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            See? This is another toast message.
        </div>
    </div>
</div>

Bootstrap Toasts Options

To customize the functionality of a toast, you can utilize various options that can be passed to the toast() method in Bootstrap. These options can be specified either through data attributes or JavaScript.

To further customize the functionality of a toast, there are various options that can be passed via data attributes or JavaScript. Using JavaScript for this purpose is preferable to avoid repetitive work.

To configure toast options using data attributes, simply add the desired option name with the data-bs- prefix, like data-bs-autohide=false or data-bs-delay=3000.

Name Type Default Description
animation boolean true Apply a CSS fade transition to the toast.
autohide boolean true Auto hide the toast.
delay number 5000 Delay hiding the toast (ms).

Although data attributes provide an easy way to set toast options, using JavaScript is preferred as it avoids repetitive tasks. You can find examples of how to set toast options using JavaScript in the methods section below.

In the example provided, the autohide option is set to false using the data attribute (line no-1), preventing the toast from automatically closing.

<div class="toast" id="myToast" data-bs-autohide="false">
    <div class="toast-header">
        <strong class="me-auto"><i class="bi-gift-fill"></i> We miss you!</strong>
        <small>10 mins ago</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body">
        It's been a long time since you visited us. We've something special for you. <a href="#">Click here!</a>
    </div>
</div>

Bootstrap Toasts Methods

Here are the standard toast methods available in Bootstrap:

Passing options: Additionally, you can pass options to the toast using an options object. For example, you can prevent the toast from closing automatically .

<script>
$(document).ready(function () {
    $("#myToast").toast({
        autohide: false
    });
});
</script>

Increase the autohide time to 10 seconds

<script>
$(document).ready(function () {
    $("#myToast").toast({
        delay: 10000
    });
});
</script>

Show: This method is utilized to show or display the toast.

<script>
$(document).ready(function(){
    $(#myBtn").click(function(){
        $("#myToast").toast("show");
    });
});
</script>

Hide: To conceal the toast, you need to explicitly invoke this function. When the autohide parameter is set to false, you'll have to call this method for the toast to disappear.

<script>
$(document).ready(function(){
    $(#myBtn").click(function(){
        $("#myToast").toast("hide");
    });
});
</script>

Bootstrap Toasts Events

Bootstrap's modal class includes several events that can be used to interact with modal functionality.

  • show.bs.toast: The event mentioned fires immediately when the show instance method is invoked.
  • shown.bs.toast: The specified event is triggered when the toast becomes visible to the user. It will wait until the CSS transition process is fully completed before being fired.
  • hide.bs.toast: The event specified is triggered immediately when the hide instance method is invoked.
  • hidden.bs.toast: The mentioned event is triggered once the toast has completed its hiding animation and is no longer visible to the user. It waits for the CSS transition process to fully complete before being fired.

For instance, the following example demonstrates how to display an alert message to the user when the fade-out transition of the toast is fully completed. Let's give it a try and observe its behavior.

<script>
$(document).ready(function () {
    $("#myToast").on("hidden.bs.toast", function () {
        alert("Toast component has been completely closed.");
    });
});
</script>

FAQ

What are Bootstrap Toasts?

Bootstrap Toasts are lightweight, unobtrusive components used to display short messages or notifications to the user. They can appear at the top or bottom of the screen and are commonly used to provide feedback about a specific action or to show alerts. Toasts are non-blocking, meaning they do not interrupt the user's workflow, and they automatically disappear after a specified duration.

How do you create a basic Bootstrap Toast?

To create a basic Bootstrap Toast, you can follow these steps:

  • Include the Bootstrap CSS and JavaScript files in your HTML document.
  • Create a container element where you want the toast to appear. This container is usually placed at the top or bottom of the page.
  • Inside the container, create a <div> element with the class toast.
  • Add the role="alert" and aria-live="assertive" attributes to the <div> for accessibility.
  • Inside the <div>, add a <div> with the class toast-header to create the header of the toast.
  • Within the header, you can include a title, close button, and other content as needed.
  • Below the header, add another <div> with the class toast-body to include the main content of the toast.

Here's an example of the HTML structure for a basic Bootstrap Toast:

<div class="toast" role="alert" aria-live="assertive">
  <div class="toast-header">
    <strong class="me-auto">Notification</strong>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    This is a simple toast message.
  </div>
</div>

How can you trigger the display of a Bootstrap Toast?

To trigger the display of a Bootstrap Toast, you'll need to use JavaScript or jQuery to control its behavior. You can use the Toast constructor in Bootstrap's JavaScript API to create a toast instance and then use its show method to make it visible. Here's an example:

var toastEl = document.querySelector('.toast');
var toast = new bootstrap.Toast(toastEl);
toast.show();

How do you handle events associated with Bootstrap Toasts?

Bootstrap Toasts provide a few events that you can listen for. Some common events include:

  • show.bs.toast: This event is triggered immediately when the show method is called on the toast.
  • shown.bs.toast: This event is triggered when the toast has been fully shown.
  • hide.bs.toast: This event is triggered immediately when the hide method is called on the toast.
  • hidden.bs.toast: This event is triggered when the toast has been fully hidden.

You can attach event listeners to the toast element to perform specific actions when these events occur. For example:

var toastEl = document.querySelector('.toast');
var toast = new bootstrap.Toast(toastEl);

toastEl.addEventListener('shown.bs.toast', function () {
  console.log('Toast shown');
});

toastEl.addEventListener('hidden.bs.toast', function () {
  console.log('Toast hidden');
});

toast.show();

How can I position Bootstrap Toasts on the screen?

Bootstrap Toasts can be positioned at the top or bottom of the screen using the position option. By default, toasts appear at the top-right corner. You can customize this by adding classes like toast-top-center, toast-top-left, toast-bottom-center, or toast-bottom-left to the .toast element. For example:

<div class="toast toast-bottom-center">
  <!-- Toast content here -->
</div>

Can I make Bootstrap Toasts dismissable?

Yes, you can make Bootstrap Toasts dismissable by adding a close button. By default, a close button is added to the toast header when you use the class btn-close. This button allows users to manually dismiss the toast. You can also use the data-bs-autohide attribute to control whether the toast will automatically hide after a certain duration.

How do I set the duration for which a Bootstrap Toast is displayed?

You can set the duration for which a Bootstrap Toast is displayed using the data-bs-delay attribute. This attribute specifies the delay in milliseconds before the toast is automatically hidden. For example:

<div class="toast" data-bs-delay="5000">
  <!-- Toast content here -->
</div>

In this example, the toast will be displayed for 5 seconds (5000 milliseconds) before automatically disappearing.

Are Bootstrap Toasts responsive?

Yes, Bootstrap Toasts are responsive by default. They adjust their size and positioning based on the screen size. However, you might need to adjust the styling or positioning classes depending on your specific design and layout requirements.

Can I customize the animation of Bootstrap Toasts?

Yes, you can customize the animation of Bootstrap Toasts using CSS. Bootstrap provides CSS classes that control the animation, such as fade and show. You can create your own animations by adding CSS transitions or animations to these classes. This allows you to control how the toast appears and disappears on the screen.

How do I use Bootstrap Toasts with jQuery?

To use Bootstrap Toasts with jQuery, make sure you have both jQuery and Bootstrap's JavaScript files included in your project. You can then use jQuery to select and manipulate toast elements. Here's an example of showing a toast using jQuery:

$(document).ready(function () {
  $('.toast').toast('show');
});

Can I include buttons or links within a Bootstrap Toast?

Yes, you can include buttons, links, or any other HTML elements within a Bootstrap Toast. You can add them directly inside the .toast-body element. This is useful when you want to provide users with actions they can take based on the notification.

How can I hide or dismiss a Bootstrap Toast programmatically?

You can hide or dismiss a Bootstrap Toast programmatically using JavaScript. If you have a reference to the toast's JavaScript object, you can call the hide method on it. For example:

var toastEl = document.querySelector('.toast');
var toast = new bootstrap.Toast(toastEl);
toast.hide();

Can I prevent a Bootstrap Toast from automatically hiding?

Yes, you can prevent a Bootstrap Toast from automatically hiding by using the data-bs-autohide="false" attribute on the .toast element. This will keep the toast visible until the user manually dismisses it using the close button.

How can I create a custom close button for a Bootstrap Toast?

To create a custom close button for a Bootstrap Toast, you can omit the default close button (btn-close) from the toast header and add your own button or element. Then, you can use JavaScript to manually dismiss the toast when your custom button is clicked. For example:

<div class="toast">
  <div class="toast-header">
    <strong class="me-auto">Notification</strong>
    <!-- Custom close button -->
    <button type="button" class="custom-close-btn">×</button>
  </div>
  <div class="toast-body">
    This is a custom toast message.
  </div>
</div>

<script>
    document.querySelector('.custom-close-btn').addEventListener('click', function () {
        var toastEl = document.querySelector('.toast');
        var toast = new bootstrap.Toast(toastEl);
        toast.hide();
    });
</script>

Are Bootstrap Toasts suitable for displaying important alerts or critical information?

While Bootstrap Toasts are generally used for non-intrusive notifications, they may not be the best choice for displaying critical information or important alerts that require immediate attention. For important alerts, you might want to consider using modal dialogs or other more attention-grabbing UI elements.

Can I style Bootstrap Toasts differently for different types of messages (success, warning, error)?

Yes, you can style Bootstrap Toasts differently for different types of messages by adding custom CSS classes to the .toast element based on the message type. For example, you could create classes like toast-success, toast-warning, and toast-error with corresponding styles. Then, you can dynamically add these classes to the toast element based on the type of message you want to display.

Can I make Bootstrap Toasts draggable or interactive?

Bootstrap Toasts do not have built-in support for being draggable or interactive in the sense of moving them around the screen. They are designed to be simple notifications. If you need more advanced interactive behavior, you might need to consider using other UI components or libraries that offer such features.

Can I use Bootstrap Toasts to display long messages or content?

While Bootstrap Toasts are typically used for short notifications, you can technically use them to display longer messages. However, keep in mind that toasts are meant to be small and unobtrusive, so displaying long content might not provide the best user experience. If you need to show more content, consider using modals or other components designed for that purpose.

Can I control the z-index of Bootstrap Toasts?

Yes, you can control the z-index of Bootstrap Toasts using CSS. By default, toasts are given a relatively high z-index value to ensure they appear above most other elements on the page. If you need to change the stacking order, you can set a custom z-index using your own CSS rules.


Conclusion

Bootstrap Toasts offer a dynamic and user-friendly way to communicate with users through notification pop-ups and alert messages. With features such as Responsive Toast Elements and Auto-Dismiss Alerts, toasts provide a seamless and engaging method for delivering important information.

The concept of Dynamic Toast Display and Popup Message Alerts ensures that users receive notifications in an interactive and visually appealing manner. Toasts are designed to be User-Friendly Alert Boxes, offering a dismissible and mobile-friendly format that adapts to various devices.

The ability to Auto-Close Toast Messages enhances the convenience for users, allowing them to focus on the content without being interrupted by persistent notifications. The inclusion of Toast Popup Styling provides developers with the flexibility to customize the appearance of toasts, making them visually appealing and on-brand.

Furthermore, the extension of functionality to include Dynamic Toast Styling, Customizable Toast Colors, and Color Variations in Toasts allows for creative and tailored designs. Toasts can be customized with a variety of colors, offering vibrant and impactful notification boxes.

The flexibility of Vertical Toast Stacking, Flexible Toast Placement, and Versatile Toast Placement allows developers to strategically position toasts on the screen, optimizing the user experience. The option for Stackable Notification Bars and Vertical Notification Stacking provides a solution for presenting multiple notifications in a clean and organized manner.