Developer Snippet Diary

ShowAlert in bootsrap 5 uisng javascript

 

<script>
function showAlert(text, type, delay, autohide, animation) {
    // defaults
    if (!text) text = "danger";
    if (!type) type = "danger";
    if (!delay) delay = 2000;
    if (autohide === undefined || autohide === "") autohide = true;
    if (animation === undefined || animation === "") animation = true;

    // create container if not exists
    let container = document.getElementById("dynamic-toast-container");
    if (!container) {
        container = document.createElement("div");
        container.id = "dynamic-toast-container";
        container.className = "toast-container position-fixed bottom-0 end-0 p-3";
        document.body.appendChild(container);
    }

    // toast element
    const toastEl = document.createElement("div");
    toastEl.className = `toast align-items-center text-white border-0 ${animation ? "" : "fade"} bg-${type}`;
    toastEl.role = "alert";
    toastEl.ariaLive = "assertive";
    toastEl.ariaAtomic = "true";

    toastEl.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">${text}</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" 
                    data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;

    container.appendChild(toastEl);

    const toast = new bootstrap.Toast(toastEl, { delay, autohide, animation });
    toast.show();

    // remove after hidden
    toastEl.addEventListener("hidden.bs.toast", () => toastEl.remove());
}
</script>

Usage:

showToast(text, type = "danger", delay = 2000, autohide = true, animation = true)


showAlert("Something went wrong");             // default: danger, 2000ms
showAlert("Task saved", "success");            // green success
showAlert("Longer info", "info", 5000);        // info for 5s
showAlert("Custom no hide", "", 3000, false);  // danger, no autohide
Posted by: R GONDAL
Email: rizikmw@gmail.com