bootstrap 5 hide existing modal using javascript

Updated: 30th March 2023
Tags: bootstrap5 javascript

In bootstrap5 to hide existing modal using javascript you need to use bootstrap.Modal.getInstance('#exampleModal').hide(); If you want to show modal with javascript we will use bootstrap.Modal.getOrCreateInstance because it maybe not initalized yet.

Here sample full sample

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

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<script>
  function hideModal() {
    bootstrap.Modal.getInstance(document.getElementById('exampleModal')).hide();
  }
  function showModal() {
    bootstrap.Modal.getOrCreateInstance(document.getElementById('exampleModal')).show();
  }
</script>