578

I am creating a modal window using Twitter Bootstrap. The default behavior is if you click outside the modal area, the modal will automatically close. I would like to disable that -- i.e. not close the modal window when clicking outside the modal.

Can someone share jQuery code to do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1296175
  • 5,831
  • 3
  • 15
  • 10
  • 2
    You may have a perfectly valid reason for doing this (and there are likely many others). However, it's worth noting that in general, UX considerations would advise against this--most users expect that clicking out of a modal will bring the content "below" to the "front." – Trevor Aug 27 '14 at 22:38
  • 33
    @Trevor That's like the opposite of [modal](http://ux.stackexchange.com/questions/12045/what-is-a-modal-dialog-window). – Rawling Sep 03 '14 at 10:22
  • 11
    what if, if there is a page at the background that can only be activated only if the user login first. By clicking the modal Ok button the user will be redirected to the login page. If the user can just clicking out, this means that the user skip the login page and just accessing the page without login. All Hell Break Loose – jumper rbk Sep 05 '14 at 01:40
  • 5
    @Trevor I don't see any evidence at all to support your claim. – 1252748 Nov 07 '14 at 21:15
  • 1
    The feature is sensible in a scenario when the user has to fill out many form fields in the modal. If the user accidentally clicks outside of the modal, then all of the entered details would be lost; then they would have to reactivate the modal and refill the fields. This feature would avoid such an irritation. – mickmackusa Dec 11 '19 at 22:56

28 Answers28

718

I believe you want to set the backdrop value to static. If you want to avoid the window to close when using the Esc key, you have to set another value.

Example:

<a data-controls-modal="your_div_id"
   data-backdrop="static"
   data-keyboard="false"
   href="#">

OR if you are using JavaScript:

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nobita
  • 23,519
  • 11
  • 58
  • 87
  • 7
    @user1296175 What was your final code to achieve this? I want to do the same. – talha2k Jul 03 '12 at 15:20
  • 4
    Thank you @nobita, add data-backdrop="static" does the trick! Twitter bootstrap document is poor :( – Blue Smith Nov 06 '12 at 14:48
  • 2
    Check answer from @@Varun Chatterji and include this on your modal definition – Leandro Bardelli May 26 '14 at 13:21
  • 1
    disable out-side click for all modals with single line of js: $.fn.modal.Constructor.DEFAULTS.backdrop = 'static'; – Lukas Liesis Mar 06 '15 at 18:52
  • There is an issue with this if you are using it for a login modal Any user can add a close button To the modal - live and just close it – VisualBean Apr 21 '15 at 11:49
  • This also disables the controls on the background. Is there a way to keep other controls active but just let the modal not close ? – vivekanon Oct 07 '15 at 19:21
  • Add these attributes to the modal's container div and not the triggering button or anchor ! – thethakuri May 17 '16 at 09:08
  • 1
    For Angular users: var modalInstance = $modal.open({ templateUrl: 'modalTemplate.html', controller: 'modalController', backdrop: 'static', }); – Alexandr May 18 '16 at 14:36
  • I found the show/hide behaviour changed when I just added the `backdrop` and `keyboard` values via javascript, but was able to fix that by additionally specifying `show`, as posted [here](http://stackoverflow.com/a/41293550/1294318). – OutstandingBill Dec 23 '16 at 00:23
  • I used the version in the comment from Lukas to disable it across all dialogs, but had to use this on Bootstrap 4: $.fn.modal.Constructor.Default.backdrop = 'static'; – Dan Harris May 08 '19 at 21:42
313

Just set the backdrop property to 'static'.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: true
})

You may also want to set the keyboard property to false because that prevents the modal from being closed by pressing the Esc key on the keyboard.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
})

myModal is the ID of the div that contains your modal content.

Nirmal
  • 9,391
  • 11
  • 57
  • 81
  • 6
    Yep, this is the cleanest, simplest answer (since it avoids adding data attributes). For reference, `backdrop` and `keyboard` are mentioned [here in their documentation](http://getbootstrap.com/javascript/#modals-usage) under the _Options_ section. – Jesse Dupuy Aug 07 '14 at 23:45
  • Are data attributes something to be avoided? Kindly guide on this. –  Sep 26 '14 at 10:08
  • @GopalAggarwal: Depends on how you setup the modal. If you associate a modal to multiple anchor tags, then using data attributes might make sense. But when there is just one modal per tag, I would go with the script parameters where every behaviour is visible in one place. – Nirmal Nov 02 '14 at 08:33
  • 7
    Also to avoid modal displaying immediately pass in show: false – Jason Parker Jan 05 '15 at 22:46
224

You can also include these attributes in the modal definition itself:

<div class="modal hide fade" data-keyboard="false" data-backdrop="static">
Varun Chatterji
  • 5,059
  • 1
  • 23
  • 24
  • 5
    Yep, this is the cleanest, simplest answer (since it works by adding data attributes). For reference, backdrop and keyboard are mentioned here in their documentation under the Options section. – jko Dec 02 '15 at 16:13
  • If you launch modal on page load this is the best way to remove other closing options. – santa Jan 30 '17 at 01:38
47

If you already have initialized the modal window, then you may want to reset the options with $('#myModal').removeData("modal").modal({backdrop: 'static', keyboard: false}) to make sure it will apply the new options.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AymKdn
  • 3,327
  • 23
  • 27
  • 2
    This helped me out. After setting the "backdrop: 'static'" the user could still close the modal with a click; seemed like a bug, but this did the trick! – Omar Dec 06 '12 at 04:26
  • 7
    For now: $('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false}); – Zamblek Jul 03 '15 at 14:44
37

Override the Bootstrap ‘hide’ event of Dialog and stop its default behavior (to dispose the dialog).

Please see the below code snippet:

   $('#yourDialogID').on('hide.bs.modal', function(e) {

       e.preventDefault();
   });

It works fine in our case.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sam Jha
  • 499
  • 4
  • 4
33

Yes, you can do it like this:

<div id="myModal"  tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true"
     data-backdrop="static"  data-keyboard="false">
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Satish Singh
  • 2,169
  • 3
  • 23
  • 32
  • This is perfect for a case where the modal is declared in the html, and only opened via javascript - ie there is no link to it. Thanks! – hgolov May 15 '16 at 09:16
22

Kind of like @AymKdn's answer, but this will allow you to change the options without re-initializing the modal.

$('#myModal').data('modal').options.keyboard = false;

Or if you need to do multiple options, JavaScript's with comes in handy here!

with ($('#myModal').data("modal").options) {
    backdrop = 'static';
    keyboard = false;
}

If the modal is already open, these options will only take effect the next time the modal is opened.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • http://stackoverflow.com/questions/16030448/convert-a-twitter-bootstrap-uncloseable-modal-into-a-closeable-one But I dont like this solution though – Victor Aug 02 '13 at 12:20
14

Just add these two things

data-backdrop="static" 
data-keyboard="false"

It will look like this now

<div class="modal fade bs-example-modal-sm" id="myModal" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">

It will disable the escape button and also the click anywhere and hide.

Vivek
  • 1,446
  • 18
  • 27
11

You can disable the background's click-to-close behavior and make this the default for all your modals by adding this JavaScript to your page (make sure it is executed after jQuery and Bootstrap JS are loaded):

$(function() {
    $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
});
Eric B
  • 321
  • 2
  • 7
6

As D3VELOPER says, the following code resolve it:

$('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});

I'm using both jquery & bootstrap and simply removeData('modal') don't work.

Jérémie Bertrand
  • 3,025
  • 3
  • 44
  • 53
5

bs 5

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<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>
</div>

bs 4.4

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
   ...
  </div>
</div>
Chester Chu
  • 395
  • 3
  • 11
4

The best I found is add this code to the link

<!-- Link -->
<a href="#mdl" role="button"  data-backdrop="static" data-keyboard="false" data-toggle="modal" id_team="" ></a>
<-- Div -->
<div id="mdl" class="modal hide fade" tabindex="-1" role="dialog" data-keyboard="false" data-backdrop="static"></div>
johnnyRose
  • 7,310
  • 17
  • 40
  • 61
3

Doing that is very easy nowadays. Just add:

data-backdrop="static" data-keyboard="false" 

In your modal divider.

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
jfindley
  • 682
  • 7
  • 6
3

Attribute names have changed in Bootstrap 5. You can use the following :

data-bs-backdrop="static" data-bs-keyboard="false"
s-79
  • 31
  • 2
2

In case anyone comes here from Google trying to figure out how to prevent someone from closing a modal, don't forget that there's also a close button on the top right of the modal that needs to be removed.

I used some CSS to hide it:

#Modal .modal-header button.close {
    visibility: hidden;
}

Note that using "display: none;" gets overwritten when the modal is created, so don't use that.

Drew
  • 1,014
  • 2
  • 10
  • 21
2

If you want to conditionally disable the backdrop click closing feature. You can use the following line to set the backdrop option to static during runtime.

Bootstrap v3.xx

jQuery('#MyModal').data('bs.modal').options.backdrop = 'static';

Bootstrap v2.xx

jQuery('#MyModal').data('modal').options.backdrop = 'static';

This will prevent an already instantiated model with backdrop option set to false (the default behavior), from closing.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
2

You can set default behavior of modal popup by using of below line of code:

 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
H_H
  • 1,460
  • 2
  • 15
  • 30
2

The updated syntax according to bootstrap 5 is as followed.
Reference Link

<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" >
SaiSurya
  • 1,046
  • 8
  • 14
1

Well, this is another solution that some of you guys might be looking for (as I was..)

My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.

The solutions presented here were not working 100%.

My solution was this:

showLocationModal = function(loc){

    var is_loading = true;

    if(is_loading === true) {

        is_loading  = false;
        var $modal   = $('#locationModal');

        $modal.modal({show:true});

        // prevent Modal to close before the iframe is loaded
        $modal.on("hide", function (e) {
            if(is_loading !== true) {
                e.preventDefault();
                return false
            }
        });

        // populate Modal
        $modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){

            is_loading = true;
     });
}};

So I temporarily prevent the Modal from closing with:

$modal.on("hide", function (e) {
    if(is_loading !== true) {
        e.preventDefault();
        return false
    }
});

But ith the var is_loading that will re enable closing after the Iframe has loaded.

miguelmpn
  • 1,859
  • 1
  • 19
  • 25
1
<button type="button" class="btn btn-info btn-md" id="myBtn3">Static 
Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">Static Backdrop</h4>
    </div>
    <div class="modal-body">
      <p>You cannot click outside of this modal to close it.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-
      dismiss="modal">Close</button>
    </div>
   </div>
  </div>
</div>
   <script>
    $("#myBtn3").click(function(){
     $("#myModal3").modal({backdrop: "static"});
    });
   });
  </script>
shiva krishna
  • 222
  • 2
  • 11
0

To Update the backdrop state in Bootstrap 4.1.3 after the modal have been Display, We used the following line from Bootstrap-Modal-Wrapper plugin. Plugin Repository code reference.

$("#yourModalElement").data('bs.modal')._config.backdrop = (true : "static");
mohamed sulibi
  • 526
  • 3
  • 12
0

Try main line with:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="verifyModalLabel" aria-hidden="true">
bharat
  • 1,762
  • 1
  • 24
  • 32
0
$(document).ready(function(e){

  $("#modalId").modal({
     backdrop: 'static',
     keyboard: false,
     show: false
  });

});

"backdrop:'static'" will prevent closing modal when clicking outside of it; "keyboard: false" specifies that the modal can be closed from escape key (Esc) "show: false" will hide the modal when the page has finished loading

edmakalla
  • 36
  • 5
0

The solution presented as an answer does not work, what is wrong?

$(document).ready(function(){
            $('.modal').modal('show');
            $('.modal').modal({
              backdrop: 'static',
              keyboard: false
            })
        });
<html>
   <head>
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/octicons@8.5.0/index.min.js"></script>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
   </head>
       <body>
       
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
              </div>
              <div class="modal-footer">
                <div class="text-right"><button type="button" class="btn btn-primary">print</button></div>
            </div>
            </div>
          </div>
        </div>
   </body>
</html>
Cristiano Felipe
  • 117
  • 1
  • 10
  • You should post this as a new question, not as an answer to an existing question. Your new question can reference this original post. – Bert Cushman Oct 28 '20 at 15:13
0

When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-bs-backdrop="static" data-bs-keyboard="false" for bootstrap 5 and data-backdrop="static" data-keyboard="false" for bootstrap 4

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap 4 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container p-5" >
      <div class="row text-center">
        <div class="col-md-6">
          <!-- Button trigger modal -->
          When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-bs-backdrop="static" data-bs-keyboard="false"
          <button type="button" class="btn btn-primary my-4" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
            Launch static backdrop 5 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">
                  <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
                  <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>
        </div>
        <div class="col-md-6">
          <!-- Button trigger modal -->
          When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-backdrop="static" data-keyboard="false"
          <button type="button" class="btn btn-primary my-4" data-toggle="modal" data-target="#exampleModal">
            Launch static backdrop 4 modal
          </button>

          <!-- Modal -->
          <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"
          data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  ...
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Save changes</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>   
    </div> 
    
    <!-- Bootstrap 5 Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Bootstrap 4 -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"></script>
  </body>
</html>
kishan maru
  • 31
  • 1
  • 3
  • 8
0

Just set static for backdrop option (backdrop: 'static'). And prevent closing the modal by pressing Esc from keyboard you have to set false for keyboard option (keyboard: false)

So, the code will be.

var jq = jQuery.noConflict();
jq(document).ready(function(){
    jq('#exampleModal').modal({backdrop: 'static', keyboard: false}); 
});
Kaizur
  • 181
  • 1
  • 10
0

Nobita's answer works for single cases, but I have like 20-30 modals on an old site and was looking for an answer that set this for every modal opened with bootstrap.

You can target the event namespace for the modal and add in default settings for every bootstrap modal.

You might not want to do this for every modal but in case you did, there's no need to statically specify each modal call.

$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this = $(this)
    var href = $this.attr('href')
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
    var option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data(), {backdrop: 'static', keyboard: false})

    e.preventDefault()

    $target
      .modal(option)
      .one('hide', function () {
        $this.focus()
      })
})

In my case, I added {backdrop: 'static', keyboard: false} to the option structure.

Thomas
  • 2,622
  • 1
  • 9
  • 16
0

If you are using bootstrap 5 or above, use the below code in modal div

<div class="modal fade customModal customModalForm" id="editPartySetting" data-bs-keyboard="false" data-bs-backdrop="static" tabindex="-1" aria-labelledby="editSettings"
aria-hidden="true" >

This will restrict user, now popup won't get closed by 'Esc' button and by clicking outside.

Goutham Harshith
  • 238
  • 2
  • 16