588

I am making a bootstrap website, with a couple of Bootstrap 'Modals'. I'm trying to customize some of the default features.

Problem is this; You can close the modal by clicking on the background. Is there anyway to disable this feature? On specifc modals only?

Bootstrap modal page

RGTest
  • 80
  • 12
Egghead
  • 6,837
  • 5
  • 20
  • 38
  • can you please tell me which event is called in this situation. $scope.ok , $scope.$dismiss i have implement for submit and abort but i don't know the event fired in this situation. – LoveToCode Mar 31 '16 at 09:01

24 Answers24

1187

On Options chapter, in the page you linked, you can see the backdrop option. Passing this option with value 'static' will prevent closing the modal.
As @PedroVagner pointed on comments, you also can pass {keyboard: false} to prevent closing the modal by pressing Esc.

If you opening the modal by js use:

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

If you are using data attributes, use:

 <button data-target="#myModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">
    Launch demo modal
 </button>`
Doguita
  • 15,403
  • 3
  • 27
  • 36
  • 1
    is there a way to keep the background able to register the clicks for other controls but just not close the modals ? – vivekanon Oct 07 '15 at 19:14
  • 5
    @mystikacid You should ask a new question for that. It will be better to help you with your problem and other users searching a similar solution. – Doguita Oct 07 '15 at 19:29
  • @Doguita : Here : http://stackoverflow.com/questions/33000898/bootstrap-modal-disable-close-on-backdrop-click-without-disabling-the-backgrou – vivekanon Oct 07 '15 at 19:33
  • 18
    Had a simple but irritating problem, make sure you place the jquery line before `$('#modal').modal('show');` Hope this helps! – cwiggo Oct 14 '15 at 09:06
  • 5
    cwiggo you don't use modal $('#modal').modal('show'); - you just use .modal({backdrop: 'static', keyboard: false}) - without any show or toggle command – TV-C-1-5 Jul 24 '17 at 19:57
  • 1
    Bootstrap 3 documentation with these options: https://getbootstrap.com/docs/3.4/javascript/#modals-options – Katie Jun 18 '19 at 20:29
  • 2
    Bootstrap 5 requires the `data-bs-toggle` and `data-bs-target` attributes. – Marco Siffert May 17 '21 at 13:04
201

This is the easiest one

You can define your modal behavior, defining data-keyboard and data-backdrop.

<div id="modal" class="modal hide fade in" data-keyboard="false" data-backdrop="static">
Sushan
  • 3,153
  • 2
  • 23
  • 21
  • 4
    This is the only thing that worked for me. Passing in the options in JS directly just didn't work for me for some reason (version 3.3.7). If anyone else corroborates, I might open an issue with the Bootstrap team. – Dennis Hackethal Feb 28 '17 at 05:13
  • 1
    At first, using js version didn't work for me too because I was setting everything after I opened the modal. You should do this "$('#modalForm').modal({ backdrop: 'static', keyboard: false });" before this "$('#modalForm').modal('show');". But for me, the best answer is from @ಅನಿಲ್ – Lucas Jun 07 '17 at 19:55
  • 1
    This worked for me. Putting the `data-backdrop="static"` option on the modal definition, not the trigger button that opens the modal as specified in other answers, worked for me. – TSmith Apr 19 '19 at 14:26
  • 2
    I've solved using only data-backdrop="static". You can see here : https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_modal_backdrop_data&stacked=h – Carmine Checker Apr 22 '21 at 05:24
106

You can use an attribute like this: data-backdrop="static" or with javascript:

$('#myModal').modal({
    backdrop: 'static',
    keyboard: false  // to prevent closing with Esc button (if you want this too)
})

See this answer too: Disallow twitter bootstrap modal window from closing

Community
  • 1
  • 1
Antonis Grigoriadis
  • 2,060
  • 2
  • 16
  • 26
47

In my application, I am using the below piece of code to show Bootstrap modal via jQuery.

 $('#myModall').modal({
                        backdrop: 'static',
                        keyboard: true, 
                        show: true
                }); 
Peter Munnings
  • 3,309
  • 1
  • 30
  • 43
ಅನಿಲ್
  • 606
  • 5
  • 7
35

You can use

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

to change the default behavior.

28

Put this code in the first block of your modal html

Bootstrap 4.x

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

Boostrap 5.x

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

Example:

<div id="modal-user" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" data-bs-keyboard="false" data-bs-backdrop="static">

Docs bootstrap 5: https://getbootstrap.com/docs/5.1/components/modal/#options

Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn't close the modal on click.

plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31
Deepa Rokhade
  • 411
  • 4
  • 4
14

Checkout This ::

$(document).ready(function() {
    $("#popup").modal({
        show: false,
        backdrop: 'static'
    });
    
    $("#click-me").click(function() {
       $("#popup").modal("show");             
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/css/bootstrap-combined.min.css" rel="stylesheet">
        </head>
    <body>
        <div class="modal" id="popup" style="display: none;">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h3>Standard Selectpickers</h3>
            </div>
            <div class="modal-body">
                
                <select class="selectpicker" data-container="body">
                    <option>Mustard</option>
                    <option>Ketchup</option>
                    <option>Relish</option>
                </select>

            </div>
            <div class="modal-footer">
                <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
                <button class="btn btn-primary">Save changes</button>
            </div>
        </div>
        <a id="click-me" class="btn btn-primary">Click Me</a> 
    </body>
        <script type="text/javascript" src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/js/bootstrap.min.js"></script>
</html>
Sachin Sanchaniya
  • 996
  • 1
  • 8
  • 16
14

There are two ways to disable click outside of bootstrap model area to close modal-

  1. using javascript

    $('#myModal').modal({
       backdrop: 'static',
       keyboard: false
    });
    
  2. using data attribute in HTML tag

    data-backdrop="static" data-keyboard="false" //write this attributes in that button where you click to open the modal popup.
    
Shehary
  • 9,926
  • 10
  • 42
  • 71
Gaurav Tripathi
  • 1,265
  • 16
  • 20
12

Another option if you do not know if the modal has already been opened or not yet and you need to configure the modal options:

Bootstrap 3.4

var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal

if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
    $modal.modal({
        keyboard: keyboard,
        backdrop: backdrop
    });
} else { // Modal has already been opened
    $modal.data('bs.modal').options.keyboard = keyboard;
    $modal.data('bs.modal').options.backdrop = backdrop;

    if(keyboard === false) { 
        $modal.off('keydown.dismiss.bs.modal'); // Disable ESC
    } else { // 
        $modal.data('bs.modal').escape(); // Resets ESC
    }
}

Bootstrap 4.3+

var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal

if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
    $modal.modal({
        keyboard: keyboard,
        backdrop: backdrop
    });
} else { // Modal has already been opened
    $modal.data('bs.modal')._config.keyboard = keyboard;
    $modal.data('bs.modal')._config.backdrop = backdrop;

    if(keyboard === false) { 
        $modal.off('keydown.dismiss.bs.modal'); // Disable ESC
    } else { // 
        $modal.data('bs.modal').escape(); // Resets ESC
    }
}

Change options to _config

Cava
  • 5,346
  • 4
  • 25
  • 41
12

Use this CSS for Modal and modal-dialog

.modal{
    pointer-events: none;
}

.modal-dialog{
    pointer-events: all;
 }

This can resolve your problem in Modal

Muthukumar
  • 121
  • 1
  • 2
8
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">

try this,During my application development ...I also met the trouble that default values for a model attribute => data-keyboard="true", => data-backdrop="non static"

Hope this will help you!

Sehdev
  • 5,486
  • 3
  • 11
  • 34
Deepalakshmi
  • 81
  • 1
  • 1
7

The solution that work for me is the following:

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

backdrop: disabled the click outside event

keyboard: disabled the scape keyword event

Jorge Santos Neill
  • 1,635
  • 13
  • 6
7

This solution worked for me:

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

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

in the button witch launch the Modal

codedge
  • 4,754
  • 2
  • 22
  • 38
6

Try this:

<div
  class="modal fade"
  id="customer_bill_gen"
  data-keyboard="false"
  data-backdrop="static"
>
Egghead
  • 6,837
  • 5
  • 20
  • 38
Vijay Chauhan
  • 1,282
  • 19
  • 18
5

if you want to change default:

for bootstrap 3.x:

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

for bootstrap 4.x and 5.x:

$.fn.modal.prototype.constructor.Constructor.Default.backdrop = 'static';
$.fn.modal.prototype.constructor.Constructor.Default.keyboard =  false;
Moin Uddin
  • 148
  • 2
  • 9
4

Use this if you want to disable the outer click for all modals using jQuery. Add this script to your Javascript after jQuery.

jQuery(document).ready(function () {
    jQuery('[data-toggle="modal"]').each(function () {
       jQuery(this).attr('data-backdrop','static');
       jQuery(this).attr('data-keyboard','false');
    });
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Disapamok
  • 1,426
  • 2
  • 21
  • 27
2

If you are using @ng-bootstrap use the following:

Component

import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss'],
})
export class ExampleComponent implements OnInit {

  constructor(
    private ngbModal: NgbModal
  ) {}

  ngOnInit(): void {
  }

  openModal(exampleModal: any, $event: any) {
    this.ngbModal.open(exampleModal, {
      size: 'lg', // set modal size
      backdrop: 'static', // disable modal from closing on click outside
      keyboard: false, // disable modal closing by keyboard esc
    });
  }
}

Template

<div (click)="openModal(exampleModal, $event)"> </div>
    <ng-template #exampleModal let-modal>
        <div class="modal-header">
            <h5 class="modal-title">Test modal</h5>
        </div>
        <div class="modal-body p-3">
            <form action="">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="">Test field 1</label>
                        <input type="text" class="form-control">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="">Test field 2</label>
                        <input type="text" class="form-control">
                    </div>

                    <div class="text-right pt-4">
                        <button type="button" class="btn btn-light" (click)="modal.dismiss('Close')">Close</button>
                        <button class="btn btn-primary ml-1">Save</button>
                    </div>
            </form>
        </div>
    </ng-template>

This code was tested on angular 9 using:

  1. "@ng-bootstrap/ng-bootstrap": "^6.1.0",

  2. "bootstrap": "^4.4.1",

Hamfri
  • 1,979
  • 24
  • 28
2

For Bootstrap 4.x, you can do like this :

$('#modal').data('bs.modal')._config.backdrop = 'static';
$('#modal').data('bs.modal')._config.keyboard = false;
STA
  • 30,729
  • 8
  • 45
  • 59
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Feb 13 '21 at 09:08
  • Also, please make the addtional insight more obvious which your answer contributes in addition to existing answers, like the one by @MoinUddin – Yunnosch Feb 13 '21 at 09:10
1

TLDR

backdrop: 'static'

https://getbootstrap.com/docs/3.3/javascript/#modals-options

specify static for a backdrop which doesn't close the modal on click.

Geoffrey Hale
  • 10,597
  • 5
  • 44
  • 45
1

none of these solutions worked for me.

I have a terms and conditions modal that i wanted to force people to review before continuing...the defaults "static" and "keyboard" as per the options made it impossible to scroll down the page as the terms and conditions are a few pages log, static was not the answer for me.

So instead i went to unbind the the click method on the modal, with the following i was able to get the desired effect.

$('.modal').off('click');

raddrick
  • 4,274
  • 2
  • 27
  • 33
0
You can Disallow closing of #signUp (This should be the id of the modal) modal when clicking outside of modal.
As well as on ESC button.
jQuery('#signUp').on('shown.bs.modal', function() {
    jQuery(this).data('bs.modal').options.backdrop = 'static';// For outside click of modal.
    jQuery(this).data('bs.modal').options.keyboard = false;// For ESC button.
})
sonu pokade
  • 377
  • 3
  • 11
0

I was missing modal-dialog that's why my close modal wasn't working properly.

Chirag Joshi
  • 409
  • 1
  • 4
  • 13
-1

You can also do this without using JQuery, like so:

<div id="myModal">

var modal = document.getElementById('myModal');
modal.backdrop = "static";
modal.keyboard = false;
Sirar Salih
  • 2,514
  • 2
  • 19
  • 18
-2

Add the below css as per you want your screen width.

@media (min-width: 991px){
    .modal-dialog {
        margin: 0px 179px !important;
    }
}
Atul
  • 1
  • 2