skip to Main Content

I’m trying to create a new toast via javascript using the bootstrap 5 toasts

so basically I searched everywhere and nothing showed up, I do not want to toggle or trigger an existing toast, all I want is to create one and show it

there are no javascript methods to create one, in bootstrap documentation, there is only create an Instance to initialize an existing one, is there a way?
https://getbootstrap.com/docs/5.2/components/toasts/

I appreciate all answers

2

Answers


  1. Chosen as BEST ANSWER

    i ended up doing this

    const toastContainer =
    `<div class="position-fixed top-0 end-0 p-3 z-index-3">
    <div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <span class="svg-icon svg-icon-2 svg-icon-primary me-3">...</span>
            <strong class="me-auto">Toast Header</strong>
            <small>11 mins ago</small>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body">
        Some text inside the toast body
        </div>
    </div>
    </div>`;
    document.body.insertAdjacentHTML('afterbegin', toastContainer);
    test = document.getElementById('toast');
    const toast = bootstrap.Toast.getOrCreateInstance(test);
    toast.show();
    

    If anyone has a more efficient or effective method, feel free to share it.


  2. The easiest way to completely create the toast with Javascript and not use an existing HTML element would be to use document.createElement() to create the HTML divs and then add the needed classes, as described here to it.

    If you want to get the following:

    <div class="toast show">
      <div class="toast-header">
        Toast Header
      </div>
      <div class="toast-body">
        Some text inside the toast body
      </div>
    </div>
    

    You would do this:

    const toastContainer = document.createElement('div');
    toastContainer.classList.add('toast', 'show');
    
    const toastHeader = document.createElement('div');
    toastHeader.classList.add('toast-header');
    toastHeader.innerText = 'Toast Header';
    
    const toastBody = document.createElement('div');
    toastBody.classList.add('toast-body');
    toastBody.innerText = 'Some text inside the toast body';
    
    toastContainer.appendChild(toastHeader);
    toastContainer.appendChild(toastBody);
    
    document.body.appendChild(toastContainer);
    

    Here I added the created divs to the body, but of course they can also be added to other divs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search