Search code examples
djangobootstrap-4toast

Bootstrap toast - Data delay not respected - Toast dont hide


After hit the submit button of a form (Ajax POST) I want to refresh the toast with the message generated in Django view. I succeed to show the message but the data-delay is not respected, the toast does not disappear after 5 sec.

<div id="messages" aria-live="polite" aria-atomic="true" style="position: relative">
        <div style="position: absolute; top: 12px; right: 12px;" >
            {% for message in messages %}
                    <div class="toast d-flex toast-success" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000">
                        <div class="toast-header toast-success shadow-none" >
                            <i class="fas fa-check"></i>
                        </div>
                        <div class="toast-body">
                            {{message}} 
                        </div>
                    </div>
            {% endfor %}
        </div>
    </div>

And in success part of Ajax, I have the following code:

$('#messages).load(location.href + " #messages>*", "") 

Solution

  • You can use setTimeout in this case:

    $("#messages").load(location.href + " #messages>*", "");
    setTimeout(function(){$("#messages").empty();}, 5000);
    

    Update

    Prevent the function set with the setTimeout() to execute:

    var myTimeout;
    
    function myFunction() {
      clearTimeout(myTimeout);
      $("#messages").load(location.href + " #messages>*", "");
      myTimeout = setTimeout(function(){$("#messages").empty();}, 5000);
    }