Home > Back-end >  Creating new toast via javascript
Creating new toast via javascript

Time:01-11

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

CodePudding user response:

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 >
  <div >
    Toast Header
  </div>
  <div >
    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.

CodePudding user response:

i ended up doing this

const toastContainer =
`<div >
<div id="toast"  role="alert" aria-live="assertive" aria-atomic="true">
    <div >
        <span >...</span>
        <strong >Toast Header</strong>
        <small>11 mins ago</small>
        <button type="button"  data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div >
    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.

  • Related