Free Web Design Code & Scripts

Bootstrap 5 Toast Dynamic Message

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

Here’s a tutorial focused on creating dynamic, customizable toast notifications using Bootstrap 5. This approach allows you to dynamically generate and display toast messages with varying content, styles, and positions on the screen.

Setting Up the Project

Include Bootstrap 5 CSS

To start, you need to include the Bootstrap 5 CSS in the <head> section of your HTML file. This provides the necessary styling for the toast component.

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

Creating the HTML Structure

Basic HTML Layout

The following HTML code sets up the structure for the input fields, select dropdowns, and a button that will trigger the toast. It also includes the toast container, where the toast messages will be appended dynamically.

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

Adding Custom Styles

Styling the Page

To enhance the visual appearance of your page, you can add custom CSS styles. This code provides a background color for the body.

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

Implementing the JavaScript Logic

JavaScript Functionality

Now, let’s add the JavaScript code to handle the dynamic toast creation. This code includes event listeners for the button click, functions to handle the toast creation, and functions to handle displaying the toast messages.

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

That’s it! You’ve successfully implemented a Bootstrap 5 Toast Dynamic Message system. You can customize the message, type, and position of the toast through the input fields and dropdowns.

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.