How to open and close modals with jQuery

Asked

Viewed 42,594 times

5

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

When I use $('#myModal').modal('show'); the modal appears but when I do $('#myModal').modal('show').delay(3000).modal('hide'); he doesn’t even show up.

2 answers

9


I don’t think it’s possible to do chain that way. I’m not 100% sure.

Anyway you can do so:

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

Example

5

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

Solution

Bootstrap > 3.0.0

You can execute a certain code when a modal is presented, making use of the event 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 is opened, the code attached to that event will be executed. In the example above, there is a 3 second pause and then the actual modal is closed.

As the method .delay() only affects the Queue of animations, the parameter 0 in the method .hide() shall be passed on to the Queue of animations and so wait for the .delay() without the parameter it is not part of the Queue and shall be executed immediately.

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>
<script src="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.