How to Prevent Modal from Closing in Bootstrap Easily
backdrop option to 'static' and keyboard option to false. This stops the modal from closing when clicking outside or pressing the escape key.Why This Happens
By default, Bootstrap modals close when you click outside the modal area or press the escape key. This happens because Bootstrap listens for these events and automatically hides the modal.
<!-- Default modal triggers closing on backdrop click and ESC key --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> Launch modal </button> <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"> Modal body content </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div>
The Fix
To stop the modal from closing on outside clicks or ESC key, set backdrop: 'static' and keyboard: false when initializing the modal. This tells Bootstrap to ignore those events.
<!-- Modal with backdrop static and keyboard false --> <button type="button" class="btn btn-primary" id="launchModal"> Launch modal </button> <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"> Modal body content </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <script> const myModal = new bootstrap.Modal(document.getElementById('exampleModal'), { backdrop: 'static', keyboard: false }); document.getElementById('launchModal').addEventListener('click', () => { myModal.show(); }); </script>
Prevention
Always set backdrop and keyboard options explicitly if you want to control modal closing behavior. Avoid relying on default settings to prevent unexpected closing.
Use Bootstrap's JavaScript API to initialize modals with options instead of only data attributes for better control.
Related Errors
Sometimes modals close unexpectedly due to event bubbling or multiple modals open at once. To fix, ensure only one modal is open and use event.stopPropagation() if needed.
Also, check for conflicting JavaScript that might trigger modal hide events.
Key Takeaways
backdrop: 'static' and keyboard: false to prevent modal closing on outside click and ESC key.