ChatGPT解决这个技术问题 Extra ChatGPT

Disallow Twitter Bootstrap modal window from closing

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?

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 That's like the opposite of modal.
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
@Trevor I don't see any evidence at all to support your claim.
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.

P
Peter Mortensen

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
});

@user1296175 What was your final code to achieve this? I want to do the same.
Thank you @nobita, add data-backdrop="static" does the trick! Twitter bootstrap document is poor :(
Check answer from @@Varun Chatterji and include this on your modal definition
disable out-side click for all modals with single line of js: $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
For Angular users: var modalInstance = $modal.open({ templateUrl: 'modalTemplate.html', controller: 'modalController', backdrop: 'static', });
N
Nirmal

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.


Yep, this is the cleanest, simplest answer (since it avoids adding data attributes). For reference, backdrop and keyboard are mentioned here in their documentation under the Options section.
Are data attributes something to be avoided? Kindly guide on this.
@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.
Also to avoid modal displaying immediately pass in show: false
V
Varun Chatterji

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

<div class="modal hide fade" data-keyboard="false" data-backdrop="static">

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.
If you launch modal on page load this is the best way to remove other closing options.
P
Peter Mortensen

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.


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!
For now: $('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});
P
Peter Mortensen

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.


then, how to revert it?
Just elegant. thx :) And @sertaconay just create a boolean variable (for instance) which will be checked to decide if u want to prevent the default
only option here that worked after a modal was opend
This is a perfect solution if you want to have finer control over when modals are closable and when they're not.
P
Peter Mortensen

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">

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!
P
Peter Mortensen

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.


stackoverflow.com/questions/16030448/… But I dont like this solution though
V
Vivek

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.


This advice was provided years earlier.
E
Eric B

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';
});

J
Jérémie Bertrand

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
johnnyRose

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>

j
johnnyRose

Doing that is very easy nowadays. Just add:

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

In your modal divider.


This advice was provided years earlier on this same page.
D
Drew

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.


Can you not also just remove the button from the modal-header?
Sometimes it's beneficial to use CSS instead of altering the HTML.
M
Mohd Abdul Mujib

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.


H
H_H

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

 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';

like +1 this method, I don't want that option for all modals.
s
s-79

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

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

C
Chester Chu

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>

m
miguelmpn

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.


s
shiva krishna
<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>

S
SaiSurya

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

<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" >

m
mohamed sulibi

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");

b
bharat

Try main line with:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="verifyModalLabel" aria-hidden="true">

e
edmakalla
$(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


C
Cristiano Felipe

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

$(document).ready(function(){ $('.modal').modal('show'); $('.modal').modal({ backdrop: 'static', keyboard: false }) });


You should post this as a new question, not as an answer to an existing question. Your new question can reference this original post.
k
kishan maru

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

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"
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"