Is there an event to get when Bootstrap Alert is shown

I have a flask app which is flashing messages to an html. In that html, when flashed messages are catched, shows a bootstrap alert. Like this:

 {% with messages = get_flashed_messages() %} 
  {% if messages %} 
    {% for message in messages %}
      <div class="alert alert-warning alert-dismissible fade show">
        <strong>{{ message }}</strong> 
        <button type="button" class="close" data-dismiss="alert">&times;</button>
      </div>
    {% endfor %} 
  {% endif %} 
{% endwith %}

All of that is working well, but I want that to disappear 'x' seconds after message is shown.

So, is there an event like this? because I didn't find anything like this on bootstrap documentation

$('#alert').on('shown', function (e) {
  // do something...
})

1 answer

  • answered 2021-05-04 23:38 Phil

    No, the alerts are part of your HTML document. They are not shown dynamically. Just write your own timeout code to dismiss the alerts

    setTimeout(() => {
      $(".alert").alert("close")
    }, 3000) // 3 seconds example
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
    
    <div class="alert alert-warning alert-dismissible fade show">
      <strong>Message #1</strong> 
      <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    <div class="alert alert-warning alert-dismissible fade show">
      <strong>Message #2</strong> 
      <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    <div class="alert alert-warning alert-dismissible fade show">
      <strong>Message #3</strong> 
      <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>