Bootstrap 5 Toast Dynamic Message

Bootstrap 5 Toast Dynamic Message
Code Snippet:Bootstrap 5 Toasts Notifications
Author: AneonTech
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 1,720
License: MIT
Edit Code online: View on CodePen
Read More

This code implements Bootstrap 5 Toast Dynamic Message functionality. It allows you to create customizable toast messages on your web page. You can specify the message content, type (e.g., success, warning), and position (e.g., top-right, bottom-left). The “Create a Toast” button triggers the display of these dynamic toast messages, providing informative feedback or alerts to users.

How to Create Bootstrap 5 Toast Dynamic Message

1. First of all, load the Bootstrap CSS by adding the following CDN link to the head tag of your website.

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

2. Inside the <body> of your HTML, create the elements for your toast messages. This includes an input field for the message content, dropdowns for selecting the type and position of the toast, and a button to trigger the toast creation.

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

3. You can customize the appearance of the toast messages generated by JS code using CSS: (Optional)

body{
  background-color: #e5e5f7;
  opacity: 0.8;
}
/* Change Toast Background Color */
.bg-success {
background-color: #YourColorHere;
}

/* Modify Toast Text Color */
.text-success {
color: #YourColorHere;
}

/* Adjust Toast Border */
.border-success {
border-color: #YourColorHere;
}

/* Change Toast Positioning (e.g., top-left) */
.toast-container {
top: 0;
left: 0;
}

/* Customize Toast Close Button (e.g., change color) */
.btn-close {
color: #YourColorHere;
}

/* Change Toast Border Radius (e.g., make them rounded) */
.toast {
border-radius: 10px;
}

4. Now, load the jQuery and Bootstrap JS by adding the following scripts at the end of the HTML code:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.min.js'></script>

5. Finally, add the following JavaScript code between <script> tag just before closing the body element. This code handles the creation and display of toast messages when the “Create a Toast” button is clicked.

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

Inside the showToast function, you can customize the appearance and behavior of your toast messages. You can change the delay, styling, and content to suit your needs.

That’s all! hopefully, you have successfully created Bootstrap 5 Toast Dynamic Message. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X