How to auto dismiss a Bootstrap 5 alert without jQuery

Viewed 630

Now that Bootstrap 5 has removed jQuery as a dependency, I was trying to find a way to automatically dismiss an Alert after a specified amount of time has passed with just raw Javascript. Below is a snippet of what I've come up with so far. Undoubtedly, there's a way to optimize this and/or perhaps a better way. If so, let me know.

<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

  <title>Hello, world!</title>
</head>

<body>
  <div id="alertID" class="alert alert-success fade show mt-1" role="alert">
    Alert text here!
  </div>

  <!-- Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>

  <!-- Autodismiss alert -->
  <script type="text/javascript">
    // Enable dismissal of an alert via JavaScript:
    var alertList = document.querySelectorAll('.alert')
    alertList.forEach(function(alert) {
      new bootstrap.Alert(alert)
    })

    // Get the alert element
    // var alertQs = document.querySelector('.alert')  // This line would target all alerts on the page
    var alertQs = document.querySelector('#alertID') // This line only targets the element with ID #alertID
    // Create a Bootstrap alert instance
    var bsAlert = bootstrap.Alert.getInstance(alertQs)
    // Dismiss alert after specified amount of time in milliseconds
    window.setTimeout(() => { bsAlert.close(); }, 2000);
  </script>
</body>
</html>

0 Answers
Related