Cray
Cray

Reputation: 5483

Close modal with second button in Bootstrap 4

I open a modal with the normal Boostrap 4 method. It works and I can open and close the modal.

But in my case I need a second button the close the modal. A simple copy of the first button wouldn't work.

I tried the following code:

$('#sitenav_close').trigger('click.dismiss.bs.modal')

It doesn't work either. Is there any other method to close a modal with a second button?

Upvotes: 0

Views: 1683

Answers (1)

terrymorse
terrymorse

Reputation: 7086

In Bootstrap 4.x, you can manually close a modal with the .modal('hide') method.

<!-- my modal -->
<div class="modal" id="myModal">
  ...
  <!-- my alternate close button -->
  <button id="altCloseButton">Alternate close</button>
  ...
</div>

<script>
  // close myModal when my alternate close button is clicked
  const altBtn = document.getElementById("altCloseButton");
  altBtn.onclick = () => $('#myModal').modal('hide');
</script>

However, if all you need is a duplicate close button, this is unnecessary, as shown below:

<!-- required Bootstrap resources -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary m-2" data-toggle="modal" data-target="#exampleModal">
  Open demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><small>.modal-title</small></h5>
      </div>
      <div class="modal-body">
        .modal-body
      </div>
      <div class="modal-footer">

        <!-- three identical close buttons -->
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close 1</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close 2</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close 3</button>

      </div>
    </div>
  </div>
</div>

Upvotes: 3

Related Questions