Explain Codes LogoExplain Codes Logo

Disable click outside of bootstrap modal area to close modal

html
modal
javascript
responsive-design
Alex KataevbyAlex Kataev·Nov 5, 2024
TLDR

To lock a Bootstrap modal so that it cannot be dismissed through mouse clicks outside the modal window, set the backdrop option to 'static':

// "I ain't going nowhere!" says the modal $('#myModal').modal({ backdrop: 'static' });

Add the keyboard option and set it to false to prevent the usage of the Escape key to close the modal:

// "Not even the Escape key can get rid of me!" adds the modal gleefully $('#myModal').modal({ backdrop: 'static', keyboard: false });

Now only an explicit action can dismiss the modal, such as invoking another JavaScript command or the user clicking a close button inside the modal.

Utilizing HTML attributes

For those who favor HTML over JavaScript for modal customization:

<!-- Adding the settings to the modal trigger element --> <button type="button" data-bs-toggle="modal" data-bs-target="#myModal" data-bs-backdrop="static" data-bs-keyboard="false"> Launch the unbreakable modal </button>

Handling multiple modals

If you are juggling multiple modals on a single page, here's how you can handle their behavior individually:

// First modal is stubborn, second modal plays nice $('#firstModal').modal({ backdrop: 'static', keyboard: false }); // "I'm not going anywhere." $('#secondModal').modal({ backdrop: true, keyboard: true }); // "Okay, I'll leave when you ask me to."

Overriding default behavior conditionally

Sometimes we need to override the default behavior conditionally. Use the hide.bs.modal event to control when the modal should close:

$('#myModal').on('hide.bs.modal', function (e) { if (!yourCustomCondition()) { e.preventDefault(); // "You shall not dismiss!" says Gandalf (the modal) } });

Common issues and easy fixes

  • Persistent Modals: Double-check the backdrop and keyboard values. A mistyped value might allow the modal to be dismissed.
  • Conflicting Modals: Ensure you're targeting the right modal. I mean, you don’t want to send an email to the wrong person, right?
  • Calibri vs Comic Sans: Always remember, Bootstrap JavaScript and third-party scripts are like Calibri and Comic Sans, they often don’t mingle well. Use the .off() method to unbind old event handlers before applying the .on() .