How to prevent Bootstrap modal from closing when clicking outside

Topic: Bootstrap / Less« Prev|Next »

Answer: Use the Modal's backdrop Option

By default, if you click outside of the Bootstrap modal window i.e. on the backdrop or dark area it will close and disappear. It also happens when you are inside the modal and press the escape key on the keyboard. But you can prevent this from happening by setting the modal's backdrop option to static and keyboard option to false, like this:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>Disallow Bootstrap Modal from Closing</title>
  • <link rel="stylesheet" href="css/bootstrap.min.css">
  • <link rel="stylesheet" href="css/bootstrap-theme.min.css">
  • <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  • <script src="js/bootstrap.min.js"></script>
  • <script type="text/javascript">
  • $(document).ready(function(){
  •     $(".show-modal").click(function(){
  •         $("#myModal").modal({
  •             backdrop: 'static',
  •             keyboard: false
  •         });
  •     });
  • });
  • </script>
  • </head>
  • <body>
  •     <!-- Button HTML (to Trigger Modal) -->
  •     <input type="button" class="btn btn-lg btn-primary show-modal" value="Show Demo Modal">
  •     
  •     <!-- Modal HTML -->
  •     <div id="myModal" class="modal fade">
  •         <div class="modal-dialog">
  •             <div class="modal-content">
  •                 <div class="modal-header">
  •                     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  •                     <h4 class="modal-title">Confirmation</h4>
  •                 </div>
  •                 <div class="modal-body">
  •                     <p>Do you want to save changes you made to document before closing?</p>
  •                     <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>
  •                 </div>
  •                 <div class="modal-footer">
  •                     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  •                     <button type="button" class="btn btn-primary">Save changes</button>
  •                 </div>
  •             </div>
  •         </div>
  •     </div>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.