How to automatically close Bootstrap 3 modal after time period

b-kat picture b-kat · Aug 30, 2014 · Viewed 61.8k times · Source

I'm struggling to automatically close Bootstrap modals after a set time period.

Here's the js code I'm using to close the modal in 4 seconds:

setTimeout(function() { $('#myModal').modal('hide'); }, 4000);

Two basic problems:

(A) When the html page (that contains the modals) loads, the modal Timeout seems to run before the modal is even displayed. The modal is set to display after clicking on a link in the page. If the link is not clicked immediately when the page loads, the modal will only appear briefly and then close immediately because essentially the Timeout period started when the html page loaded, not when the modal was displayed.

(B) If the user clicks on the link to launch the modal a second time (or 3rd time, 4th time, etc.), the modal displays properly but does NOT close after the time period. It just stays open until the user manually closes it.

So...the two questions are:

(1) How do I get the modal Timeout period to wait until the modal is displayed before running the clock.

(2) How do I get the modal to display a second and third time with the proper Timeout function still working?

(The answer(s) proposed at this link below looked promising, but aren't working for me. Maybe they don't work on Bootstrap 3? How to automatically close the bootstrap modal dialog after a minute )

This code below looked very promising, but didn't work even after changing 'shown' to 'shown.bs.modal'. Or maybe I'm placing this code in the wrong place?

var myModal = $('#myModal').on('shown', function () {
    clearTimeout(myModal.data('hideInteval'))
    var id = setTimeout(function(){
        myModal.modal('hide');
    });
    myModal.data('hideInteval', id);
})

Many thanks for any suggestions!

Answer

Aguardientico picture Aguardientico · Aug 30, 2014

I'm not pretty sure about your html so I did a complete example:

html:

<a data-toggle="modal" href="#myModal" class="btn btn-primary">Open Modal</a>

<div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                <h4>Header</h4>
            </div>
            <div class="modal-body">
                Modal Content
            </div>
        </div> 
    </div>
</div>

js:

$(function(){
    $('#myModal').on('show.bs.modal', function(){
        var myModal = $(this);
        clearTimeout(myModal.data('hideInterval'));
        myModal.data('hideInterval', setTimeout(function(){
            myModal.modal('hide');
        }, 3000));
    });
});

The main difference with your code:

  1. I set a time for timeout (3000)
  2. I set myModal variable inside callback