Bootstrap 3 open only one modal at time

How to close opened modals when opening a new one

The Code

Demo
Demo
Demo and source code

Sometime you need to have only one modal active each time, with this simple javascript you can have the opened modal close when opening a new one.

If you want you can set a custom class (ex: .modal.modal-unique instead of .modal) to limit the functionality only to some modals.

// close opened .modal on opening new modal
// you can give custom class like this // var modalUniqueClass = ".modal.modal-unique";

var modalUniqueClass = ".modal";
$('.modal').on('show.bs.modal', function(e) {
  var $element = $(this);
  var $uniques = $(modalUniqueClass + ':visible').not($(this));
  if ($uniques.length) {
    $uniques.modal('hide');
    $uniques.one('hidden.bs.modal', function(e) {
      $element.modal('show');
    });
    return false;
  }
});