Disallow Twitter Bootstrap modal window from closing
Asked Answered
N

29

583

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?

Nusku answered 27/3, 2012 at 17:10 Comment(5)
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."Caiman
@Caiman That's like the opposite of modal.Borries
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 LooseDanndanna
@Caiman I don't see any evidence at all to support your claim.Clydesdale
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.Thermy
C
720

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
});
Curl answered 27/3, 2012 at 17:18 Comment(10)
@Nusku What was your final code to achieve this? I want to do the same.Perky
Thank you @nobita, add data-backdrop="static" does the trick! Twitter bootstrap document is poor :(Attainable
Check answer from @@Varun Chatterji and include this on your modal definitionHottentot
disable out-side click for all modals with single line of js: $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';Stonework
There is an issue with this if you are using it for a login modal Any user can add a close button <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> To the modal - live and just close itSweetbrier
This also disables the controls on the background. Is there a way to keep other controls active but just let the modal not close ?Derouen
Add these attributes to the modal's container div and not the triggering button or anchor !Fredenburg
For Angular users: var modalInstance = $modal.open({ templateUrl: 'modalTemplate.html', controller: 'modalController', backdrop: 'static', });Ripe
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.Farrica
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';Pownall
T
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.

Tiffin answered 12/7, 2012 at 0:36 Comment(4)
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.Krigsman
Are data attributes something to be avoided? Kindly guide on this.Bluebell
@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.Tiffin
Also to avoid modal displaying immediately pass in show: falseVisa
Z
224

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

<div class="modal hide fade" data-keyboard="false" data-backdrop="static">
Zajac answered 9/1, 2013 at 3:34 Comment(2)
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.Betty
If you launch modal on page load this is the best way to remove other closing options.Jointless
S
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.

Spumescent answered 19/7, 2012 at 16:41 Comment(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!Surrounding
For now: $('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});Bonacci
B
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.

Buchalter answered 6/8, 2014 at 11:54 Comment(4)
then, how to revert it?Kodiak
Just elegant. thx :) And @Kodiak just create a boolean variable (for instance) which will be checked to decide if u want to prevent the defaultImpressionable
only option here that worked after a modal was opendSecunderabad
This is a perfect solution if you want to have finer control over when modals are closable and when they're not.Michael
I
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">
Iluminadailwain answered 1/1, 2015 at 17:54 Comment(1)
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!Matlock
H
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.

Hurdle answered 25/4, 2013 at 22:10 Comment(1)
#16030948 But I dont like this solution thoughTananarive
E
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.

Elevenses answered 16/5, 2014 at 17:55 Comment(1)
This advice was provided years earlier.Thermy
M
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';
});
Moleskins answered 30/9, 2014 at 20:5 Comment(0)
M
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.

Mallorie answered 16/9, 2015 at 8:31 Comment(0)
C
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>
Calton answered 30/5, 2022 at 4:16 Comment(0)
C
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>
Chambless answered 15/5, 2014 at 16:52 Comment(0)
P
3

Doing that is very easy nowadays. Just add:

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

In your modal divider.

Protolithic answered 24/4, 2016 at 6:50 Comment(1)
This advice was provided years earlier on this same page.Thermy
F
3

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

data-bs-backdrop="static" data-bs-keyboard="false"
Fissionable answered 13/8, 2021 at 8:34 Comment(0)
F
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.

Fictive answered 2/5, 2014 at 15:27 Comment(2)
Can you not also just remove the button from the modal-header?Enriqueenriqueta
Sometimes it's beneficial to use CSS instead of altering the HTML.Fictive
G
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.

Gurango answered 18/11, 2016 at 15:30 Comment(0)
C
2

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

 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
Consequently answered 16/2, 2017 at 8:11 Comment(1)
like +1 this method, I don't want that option for all modals.Prothalamion
T
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" >
Tessitura answered 30/11, 2021 at 7:32 Comment(0)
D
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.

Damiondamita answered 13/4, 2015 at 14:1 Comment(0)
S
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>
Stockholder answered 6/7, 2017 at 9:49 Comment(0)
K
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");
Komsa answered 4/9, 2018 at 19:4 Comment(0)
S
0

Try main line with:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="verifyModalLabel" aria-hidden="true">
Seyler answered 18/7, 2020 at 12:26 Comment(0)
H
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

Household answered 19/9, 2020 at 13:7 Comment(0)
T
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/[email protected]/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/[email protected]/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>
Tripod answered 28/10, 2020 at 14:38 Comment(1)
You should post this as a new question, not as an answer to an existing question. Your new question can reference this original post.Van
F
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/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap 4 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/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/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
  </body>
</html>
Freytag answered 19/4, 2022 at 5:43 Comment(0)
W
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}); 
});
Workmanlike answered 21/10, 2022 at 9:15 Comment(0)
J
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.

Jaredjarek answered 15/11, 2022 at 21:47 Comment(0)
S
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.

Swain answered 11/5, 2023 at 13:28 Comment(0)
D
0

If you are using Bootstrap 5 or later, it's recommended to use data-bs-backdrop and data-bs-keyboard. If you are using Bootstrap 4 or an earlier version, you can use data-backdrop and data-keyboard. Ensure that you are using the correct attribute based on the version of Bootstrap you are working with.

v5

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

v4

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

https://getbootstrap.com/docs/5.2/components/modal/#static-backdrop

Dachau answered 14/12, 2023 at 1:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.