Bootstrap Toasts


In this tutorial you will learn how to use the Bootstrap toast component.

Creating the Toasts with Bootstrap

The toast component is newly introduced in Bootstrap 4. They are lightweight notifications similar to push notifications that are shown by web browsers on computer screens. They’re built with flexbox, so you can easily align and position them on a web page.

Additionally, toasts are opt-in for performance reasons, so you must initialize them yourself with toast() method. Also, toasts will automatically hide after 5000 milliseconds (5 seconds), if you do not specify autohide: false option. Now let’s see how to create a toast.

Step 1: Adding the Toast Markup

Toasts markups are pretty straightforward. The following example will show you how to create a toast component with a header, body, and a close button.

Example

<div class="toast" id="myToast">
    <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>

Step 2: Triggering the Toasts

Toasts can be triggered via JavaScript — just call the toast() Bootstrap method with the idclass or any CSS selector of the target element in your JavaScript code.

Example

jQuery JavaScript

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

— The output of the above example will look something like this:

Bootstrap Toast

Changing the Toast’s Color Schemes

You can use the color and background utility classes to create toasts with different color schemes.

The following example will create a toast with blue background and white text.

Example

<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>

— The output of the above example will look something like this:

Bootstrap Toast with Different Color Schemes

Leave a Reply

Your email address will not be published. Required fields are marked *