bootstrap modal popup disable click outside

How to Disable Click Outside of Bootstrap Modal Popup?

If you are using Bootstrap Modal Popup in your web application, you might want to disable the click outside of the modal popup. This will prevent the user from closing the modal by clicking outside of it.

There are a few ways to achieve this:

Method 1: Using data-backdrop Attribute

You can use the data-backdrop attribute to disable the click outside of the modal. Set the value of the attribute to "static".

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
  <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" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</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>

In the above code, the data-backdrop attribute is set to "static". This will disable the click outside of the modal.

Method 2: Using jQuery

You can also disable the click outside of the modal using jQuery. Here's an example:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <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" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</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>

<script>
  $(document).ready(function(){
    $('#myModal').modal({
      backdrop: 'static',
      keyboard: false
    });
  });
</script>

In the above code, we are using the modal() method of jQuery to initialize the modal. We are setting the backdrop property to "static" and keyboard property to false. This will disable the click outside of the modal and also prevent the user from closing the modal using the keyboard.

These are the two ways to disable click outside of Bootstrap Modal Popup. Choose the one that suits your requirements the best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe