Display a bootstrap toast using a JavaScript class method

One way to display a bootstrap toast is by using the following code snippet:

let my_toast = new myToast('title', 'hello world');
my_toast.show();

Currently, I am loading the HTML content from an external file named myToast.html:

  <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
<div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
    <img src="" class="rounded me-2" alt="">
    <strong class="me-auto">
      <div id="toast-title">
        Bootstrap
      </div>
    </strong>
    <small><div id=""></div></small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div id="toast-body" class="toast-body">
        Hello, world! This is a toast message.
    </div>
</div>
</div>

By adding this HTML content to a

<div id="mydiv"></div>
on the main page, updating the title and body accordingly, and then calling the Tost.show() method:

<script>
    class myToast{
        toast_html; 

        constructor(title, message) {
            this.title = title;
            this.message = message;

            let template_html;
            $.ajax({
                async: false,
                type: 'GET',
                url: "myToast.html",
                success: function(data) {
                    template_html = data;
                }
            });

            let toast_div = document.createElement("div");
            toast_div.id = "toast_wrapper";              
            toast_div.innerHTML = template_html;            
            toast_div.querySelector("#toast-title").innerHTML = (this.title);
            toast_div.querySelector("#toast-body").innerHTML = (this.message);

            this.toast_html = toast_div;
        }
    }

    let to = new myToast('title', 'hello world');
    $("#mydiv").append(to.toast_html);

    var toastLiveExample = document.getElementById('liveToast');
    var toast = new bootstrap.Toast(toastLiveExample);

    toast.show();
</script>

Is there a more efficient or concise solution available?

Answer №1

In order to streamline your code and avoid unnecessary ajax calls to an external HTML template, consider transferring your HTML template code to JavaScript. This approach allows for easy customization of the layout of a toast message, such as creating danger, success, info, or warning toast types. The key is to create elements during the initialization of the Toast class.

Below is an implementation that you can test:

Ref: Bootstrap 5 Toast - getOrCreateInstance

/* Custom Implementation */
function Toast(title, description) {
    var toastElement = buildToast(title, description);
    var toastWrapper = getOrCreateToastWrapper();
    toastWrapper.append(toastElement);
    this.bootstrapToast = bootstrap.Toast.getOrCreateInstance(toastElement);
    
    this.show = function() {
        this.bootstrapToast.show();
    }
    
    this.hide = function() {
        this.bootstrapToast.hide();
    }
    
    this.dispose = function() {
        this.bootstrapToast.dispose();
    }
}

/* Sample Call-to-Action Example */
var title = 'Bootstrap';
var description = 'Hello, world! This is a toast message.';
var toast = new Toast(title, description);
toast.show();

/* Utility Functions */
function getOrCreateToastWrapper() {
    var toastWrapper = document.querySelector('body > [data-toast-wrapper]');
    
    if (!toastWrapper) {
        toastWrapper = document.createElement('div');
        toastWrapper.style.zIndex = 11;
        toastWrapper.style.position = 'fixed';
        toastWrapper.style.bottom = 0;
        toastWrapper.style.right = 0;
        toastWrapper.style.padding = '1rem';
        toastWrapper.setAttribute('data-toast-wrapper', '');
        document.body.append(toastWrapper);
    }
    
    return toastWrapper;
}

function buildToastHeader(title) {
    var toastHeader = document.createElement('div');
    toastHeader.setAttribute('class', 'toast-header');
    
    var img = document.createElement('img');
    img.setAttribute('class', 'rounded me-2');
    img.setAttribute('src', '');
    img.setAttribute('alt', '');
    
    var strong = document.createElement('strong');
    strong.setAttribute('class', 'me-auto');
    strong.textContent = title;
    
    var closeButton = document.createElement('button');
    closeButton.setAttribute('type', 'button');
    closeButton.setAttribute('class', 'btn-close');
    closeButton.setAttribute('data-bs-dismiss', 'toast');
    closeButton.setAttribute('data-label', 'Close');
    
    toastHeader.append(img);
    toastHeader.append(strong);
    toastHeader.append(closeButton);

    return toastHeader;
}

function buildToastBody(description) {
    var toastBody = document.createElement('div');
    toastBody.setAttribute('class', 'toast-body');
    toastBody.textContent = description;
    
    return toastBody;
}

function buildToast(title, description) {
    var toast = document.createElement('div');
    toast.setAttribute('class', 'toast');
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    var toastHeader = buildToastHeader(title);
    var toastBody = buildToastBody(description);
    
    toast.append(toastHeader);
    toast.append(toastBody);
    
    return toast;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a4845455e595e584b5a6a1f041a0418">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d7dadac1c6c1c7d4c5f5809b859b87">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

Develop a unique Kotlin/JS WebComponent featuring custom content

I am trying to create a custom tag using Kotlin that includes default content. While the example I found works well, I am having trouble adding default content (such as an input element) inside the custom tag. After attempting various approaches, I have o ...

Retrieve the location within the parent mesh

In my scenario, I have a series of meshes organized in a hierarchy as follows: Scene -scene.add(SpaceMesh) -SpaceMesh.add(ShipMesh) SpaceMesh is currently in motion within the scene. However, ShipMesh remains stationary. When I request th ...

When using Node.js with Mongoose, you will receive a single object value instead of multiple values in an array

data=[{ locId: '332wn', locadetails: [ { loc: 'ny', status: true }, { loc: 'ca', status: null ...

The robot will automatically update its own message after a designated period of time

I am facing an issue with my code where the bot is not updating its message after a specific time period defined by time.milliseconds * 1000. How can I make the bot edit its message after that duration? let timeout = 15000; if (author !== null && ...

Is your bootstrap tooltip appearing in a different location than your mouse cursor on mouse move?

When hovering over multiple images, I want the tooltip to follow the mouse according to this solution. However, sometimes the tooltip appears very far away from the mouse and flickers. Does anyone know why? Additionally, the CSS code provided below doesn& ...

The responsiveness issue with the Bootstrap button menu in my Django project is causing functionality problems

I am currently working on a Django project and have set up a static folder in my "accueil" application. However, when I resize the browser window, the button to show the menu does not function as expected. The template I downloaded for free is not working ...

Adding numerous objects to a Vuex store using mutations

I am currently working with the following store setup: import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ plugins: [createPersistedState()], state: { ...

How can you maintain the "link" text in a div while removing the final hyperlink?

I am currently designing a breadcrumb navigation for a website. The breadcrumbs are generated using a templating language before the page is displayed. However, after rendering the page, I need to make some adjustments. Instead of using multiple IF/ELSE s ...

Unlocking the Chrome performance tool summary using SeleniumDiscovering the Chrome performance tool

I'm looking to utilize the Chrome performance tool for analyzing my website and then extract a summary of the results using Selenium WebDriver in Java. Despite extensive searching, I haven't been able to find a suitable solution yet. To give you ...

React Weather App: difficulties entering specific latitude and longitude for API requests

I have successfully developed an app that displays the eight-day weather forecast for Los Angeles. My next objective is to modify the longitude and latitude in the API request. To achieve this, I added two input fields where users can enter long/lat values ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...

What is the best way to enlarge an element when scrolling downwards within the element?

I am looking to create a div that dynamically adjusts its height based on the user's scrolling behavior. The goal is for the div to expand to the very top as the user scrolls downward, and stop when it reaches 70% of the container/parent element. Is t ...

Update the SQL database by transferring star ratings from a JSP file

Utilizing JSP to showcase information obtained from user queries, I have implemented a system where contextual data and the query itself are saved in a MySQL database using JDBC each time a new query is input. To enhance user interaction, I wanted to incor ...

React Application Issue: Unable to successfully redirect to the homepage upon logging in

Attempting to create a web application with the MERN stack is causing some trouble when trying to redirect users to the home page post-login. Here's how it should ideally function: User inputs login details The server validates these details and gene ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

Unable to display image source in viewport

Currently, I am working on developing a basic ionic app that interacts with an API that I have created. I am encountering an issue where all data is being displayed correctly in the view except for the src attribute of an image. When I use console.log to c ...