Search code examples
javascripttoastbootstrap-5

How to initialize toasts with JavaScript in Bootstrap 5?


I can't initialize Bootstrap 5 Toasts.

The button to initialize the toast:

<button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button>

My JavaScript:

document.getElementById("toastbtn").onclick = function() {
        var toastElList = [].slice.call(document.querySelectorAll('.toast'))
        var toastList = toastElList.map(function(toastEl) {
          return new bootstrap.Toast(toastEl, option)
        })
      };

JSfiddle: https://jsfiddle.net/5e1t3scp/

And here's the documentation.

The JavaScript has been taken from Bootstrap's website. I tried many times but couldn't initialize it. What am I doing wrong? Thanks in advance!


Solution

  • Since the second parameter of the constructor is optional, it is unnecessary. However, if you would like to supply options, you should do so in the form of an object:

    // Defaults according to the documentation
    {
      animation: true,
      autohide: true,
      delay: 500
    }
    

    <!doctype html>
    <html lang="en">
    
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
      </head>
    
      <body>
    
        <div class="container mt-5">
    
          <!-- button to initialize toast -->
          <button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button>
    
          <!-- Toast -->
          <div class="toast">
            <div class="toast-header">
              <strong class="mr-auto">Bootstrap</strong>
              <small>11 mins ago</small>
              <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">
                <span>&times;</span>
              </button>
            </div>
            <div class="toast-body">
              Hello, world! This is a toast message.
            </div>
          </div>
    
        </div>
    
    
        <!-- Popper.js first, then Bootstrap JS -->
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
        <script>
          document.getElementById("toastbtn").onclick = function() {
            var toastElList = [].slice.call(document.querySelectorAll('.toast'))
            var toastList = toastElList.map(function(toastEl) {
            // Creates an array of toasts (it only initializes them)
              return new bootstrap.Toast(toastEl) // No need for options; use the default options
            });
           toastList.forEach(toast => toast.show()); // This show them
       
            console.log(toastList); // Testing to see if it works
          };
    
        </script>
      </body>
    
    </html>