Free Web Design Code & Scripts

Bootstrap 5 Toast Dynamic Message

Bootstrap 5 Toast Dynamic Message
Code Snippet:Bootstrap 5 Toasts Notifications
Author: AneonTech
Published: 6 months ago
Last Updated: 6 months ago
Downloads: 129
License: MIT
Edit Code online: View on CodePen
Read More

Creating dynamic Bootstrap toasts allows you to display contextual, non-disruptive messages to your users. This tutorial guides you through the process of creating a Bootstrap 5 Toast Dynamic Message system where you can control the content, type, and position of the toast notifications.

Adding Bootstrap CSS

To begin, you need to include the Bootstrap CSS in your project. This can be done by adding the following link tag to the “ section of your HTML document.

 <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css'>

Creating the HTML Structure

Next, build the HTML structure for your toast generator. This includes input fields for the toast content, type (color), and position, as well as a button to trigger the toast. Also, a `toast-container` div is created to hold the toasts.

 <body>
    <div class="container">
        <div class="row py-5 text-center">
            <div class="col-12 input-group">
                <input type="text" class="form-control" name="content" placeholder="Toast content">
                <select class="form-select" name="type">
                    <option value="" selected>Toast type</option>
                    <option value="primary">Primary</option>
                    <option value="secondary">Secondary</option>
                    <option value="success">Success</option>
                    <option value="danger">Danger</option>
                    <option value="warning">Warning</option>
                    <option value="info">Info</option>
                    <option value="light">Light</option>
                    <option value="dark">Dark</option>
                </select>
                <select class="form-select" name="position">
                    <option value="" selected>Toast position</option>
                    <option value="top-0,end-0">Top Right</option>
                    <option value="bottom-0,end-0">Bottom Right</option>
                    <option value="bottom-0,start-0">Bottom Left</option>
                    <option value="top-0,start-0">Top Left</option>
                </select>
                <button id="create-toast" class="btn btn-primary">Create a Toast</button>
            </div>
        </div>
    </div>
    <div aria-live="polite" aria-atomic="true">
        <div class="toast-container position-absolute p-3" id="toast-container" style="z-index:9;"></div>
    </div>
 </body>

Styling the Page with CSS

To enhance the visual appeal, add some CSS to your page. This example focuses on the background color, but you can customize it further.

body{
  background-color: #e5e5f7;
  opacity: 0.8;
}

Implementing the Toast Logic with JavaScript

The JavaScript code handles the creation and display of the dynamic toasts. It listens for a click event on the “Create a Toast” button, retrieves the values from the input fields, and then calls the `showToast` function to display the toast.

document.querySelector('#create-toast').addEventListener('click', function() {
    document.querySelector('#toast-container').classList.remove('top-0','end-0','bottom-0','start-0');

    var content = (document.querySelector('input[name=content]').value != '') 
        ? document.querySelector('input[name=content]').value 
        : 'Lorem ipsum dolor sit amet';

    var type = (document.querySelector('select[name=type]').value != '') 
        ? document.querySelector('select[name=type]').value 
        : 'success';

    var position = (document.querySelector('select[name=position]').value != '') 
        ? document.querySelector('select[name=position]').value.split(',')
        : ['top-0','end-0'];

    showToast(content, type, position);
});

function showToast(content, type, position) {
    var delay = 15000;
    position.forEach((el) => {
        document.querySelector("#toast-container").classList.add(el);
    });
    var html = `<div class="toast align-items-center text-white bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true"><div class="d-flex"><div class="toast-body h6 p-3 m-0">${content}</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button></div></div>`;
    var toast = htmlToElement(html);
    var toastContainer = document.querySelector("#toast-container");
    toastContainer.appendChild(toast);
    var toast = new bootstrap.Toast(toast, {delay:delay, animation:true});
    toast.show();
    setTimeout(() => toast.remove(), delay + 15000);
}

function htmlToElement(html) {
    var template = document.createElement('template');
    html = html.trim();
    template.innerHTML = html;
    return template.content.firstChild;
}

By following these steps, you have successfully created a system for generating Bootstrap Toast Dynamic Message notifications. You can now easily display dynamic, contextual messages to your users with customizable content, type, and position.

Loading... ...

Loading preview...

Device: Desktop
Dimensions: 1200x800
Lines: 0 Characters: 0 Ln 1, Ch 1

Leave a Comment

About W3Frontend

W3Frontend provides free, open-source web design code and scripts to help developers and designers build faster. Every snippet is reviewed before publishing for quality. Learn more.