javascriptbootstrap-modalbootstrap-5blur

Bootstrap modal hides when it loses focus to main page


When my Boostrap Modal is displayed and it loses focus by the user clicking off the modal and onto the main page, the Modal is hidden. How can I stop this?

on('hidden.bs.modal') gets triggered after the modal has gone so e.preventDefault() is not useful.

Is there a Bootstrappy way to control this or do I have to try and intercept the click and if the target's antecedent isn't the modal I prevent the default action?


Solution

  • Use a static backdrop by adding the attributes data-bs-backdrop="static" (and optionally, data-bs-keyboard="false" if you don't want the user to be able to escape using the esc key on their keyboard) onto the modal element

    From https://getbootstrap.com/docs/5.3/components/modal/#static-backdrop:

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
      Launch static backdrop modal
    </button>
    
    <!-- Modal -->
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
            <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">Understood</button>
          </div>
        </div>
      </div>
    </div>