How to open and close modals with jQuery

3

I'm trying to open a modal, wait 3 seconds, and close it within $( document ).ready() .

When I use $('#myModal').modal('show'); the modal appears but when I do $('#myModal').modal('show').delay(3000).modal('hide'); it does not even appear.

    
asked by anonymous 29.03.2014 / 22:08

2 answers

3

I do not think it's possible to do chain like this. I'm not 100% sure of that.

Either way you can do this:

$('#myModal1').modal('show');
setTimeout(function () {
    $('#myModal1').modal('hide')
}, 2000);

Example

    
29.03.2014 / 22:17
3

Your problem is that you are using the .delay() method incorrectly. The same only affects the queue of animations and not other methods, functions, events, etc. that are not in queue .

Solution

Bootstrap > 3.0.0

You can execute certain code when a modal is displayed, making use of the shown.bs.modal :

$('#myModal1').on('shown.bs.modal', function() {

    var $me = $(this);

    $me.delay(3000).hide(0, function() {
        $me.modal('hide');
    });
});

So when the modal opens, the code appended to that event will be executed. In the example above, there is a pause of 3 seconds and then the modal itself is closed.

As the .delay() method only affects the queue of animations, the 0 in the .hide() method is passed so that it is included in the queue of animations and thus wait for the .delay() indicated, without the parameter it is not part of queue > so it runs right away.

Example

Example below also in JSFiddle .

$(function() {

  $('#myModal1').on('shown.bs.modal', function() {

    var $me = $(this);

    $me.delay(3000).hide(0, function() {
      $me.modal('hide');
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal1">
 Abrir, deve fechar ao fim de 3 segundos
</button>
    
30.03.2015 / 17:42