Close Bootstrap Modal
Asked Answered
F

30

549

I have a bootstrap modal dialog box that I want to show initially, then when the user clicks on the page, it disappears. I have the following:

$(function () {
   $('#modal').modal(toggle)
});

 <div class="modal" id='modal'>
     <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Error:</h3>
        </div>
        <div class="modal-body">
        <p>Please correct the following errors:</p>
        </div>
     </div>
 </div>

The modal is displayed initially, but it does not close when clicked outside of the modal. Also, the content area is not greyed out.. How can I get the modal to display initially, then close after the user clicks outside the area? And how can I get the background to be grayed out as in the demo?

Fusilier answered 11/5, 2013 at 2:49 Comment(2)
Are you initializing your modal with $("#yourModal").modal() or $('.modal').modal()?Systaltic
https://mcmap.net/q/74607/-close-jquery-modal/…Desirable
E
859

Put modal('toggle') instead of modal(toggle)

$(function () {
   $('#modal').modal('toggle');
});
Enumerate answered 11/5, 2013 at 3:19 Comment(6)
Including the 'toggle' at all is superflous. Just make sure not to have a 'hide' class on the modal div. But yes, the typo was causing the issue. so +1Systaltic
no it does not work as intended, it hides the modal element but the background overlay element still exists, you should use the @Subodth solution.Seidule
@Pierre - consider removing your comment, .modal().hide() is not the same as .modal('hide'), you are going to confuse people.Secrest
Like Parik said, the correct answer is using modal('hide')Handoff
This is no working in case of a modal on another modal. Thanks.Contamination
Brilliant. Been stuck for hours. This is exactly what I needed. Was opening a new modal object after closing another and calling toggle on both in my function worked perfectly. Thanks so much!Splitting
A
510

to close bootstrap modal you can pass 'hide' as option to modal method as follow

$('#modal').modal('hide');

Please take a look at working fiddle here

bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation

If none of the above method work, give a id to your close button and trigger click on close button.

Astoria answered 25/11, 2013 at 11:16 Comment(2)
$('#modal').modal('toggle'); better to hide modal shadowJello
@hamzeh.hanandeh, toggle keeps the overlay and is not a solution. You should always use either show or hide.Benthos
S
121
$('#modal').modal('toggle'); 

or

$('#modal').modal().hide();

should work.

But if nothing else works you can call the modal close button directly:

$("#modal .close").click()
Shanonshanta answered 9/6, 2016 at 12:4 Comment(5)
the one with hide() closes the modal but leaves the background blurred. $("#modal .close").click() does it perfectly. Thank you!Erdmann
This is clearly documented already, here is no need to fake a click, that seems pretty janky. The correct answer is: $('#modal').modal('hide');Secrest
this -> $('#modal').modal().hide();Lorenz
I have a model which does not close with $('#modal').modal('hide') however i can close it using $('#modal').modal('toggle') but that display a vertical scroll bar after closing. So for me $('#modal').hide() worked perfectly but i wanna know if would that create any problems ? And i am coding inside $('#modal .close').click() so i don't think i could use it to close modal.Pinkney
$("#modal .close").click() nice solution!! :)Bedew
B
49

this worked for me:

<span class="button" data-dismiss="modal" aria-label="Close">cancel</span>

use this link modal close

Bathy answered 12/12, 2015 at 12:15 Comment(0)
D
34

Try This

$('#modal_id').modal('hide');
Defazio answered 16/7, 2019 at 5:47 Comment(3)
I think this provides an answer to the question.Southeastward
I agree. This answer is more accurate to the question.Mullen
@MarceloAgimóvel :-)Defazio
M
22
$("#your-modal-id").modal('hide');

Running this call via class ($(".my-modal")) won't work.

Melisent answered 5/12, 2016 at 10:22 Comment(0)
F
17

this one is pretty good and it also works in angular 2

$("#modal .close").click()
Foggy answered 1/3, 2017 at 5:58 Comment(1)
Works for me instead of $('#modal').modal('toggle'); which has no effect.Noahnoak
O
14

You can see this reference but if this link has been removed, read this description:

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal(options)

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-backdrop="".

|-----------|-------------|--------|---------------------------------------------|
| Name      | Type        | Default| Description                                 |
|-----------|-------------|--------|---------------------------------------------|
| backdrop  | boolean or  | true   | Includes a modal-backdrop element.          |
|           | the string  |        | Alternatively, specify static for a         |
|           | 'static'    |        | backdrop which doesn't close the modal      |
|           |             |        | on click.                                   |
|           |             |        |                                             |
| keyboard  | boolean     | true   | Closes the modal when escape key is pressed.|   
|           |             |        |                                             |
| focus     | boolean     | true   | Puts the focus on the modal when initialized|       
|           |             |        |                                             |
| show      | boolean     | true   | Shows the modal when initialized.           |
|-----------|-------------|--------|---------------------------------------------|

Methods

Asynchronous methods and transitions

All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.

See our JavaScript documentation for more information.

.modal(options)

Activates your content as a modal. Accepts an optional options object.

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

.modal('toggle')

Manually toggles a modal. Returns to the caller before the modal has actually been shown or hidden (i.e. before the shown.bs.modal or hidden.bs.modal event occurs).

$('#myModal').modal('toggle')

.modal('show')

Manually opens a modal. Returns to the caller before the modal has actually been shown (i.e. before the shown.bs.modal event occurs).

$('#myModal').modal('show')

.modal('hide')

Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the hidden.bs.modal event occurs).

$('#myModal').modal('hide')

.modal('handleUpdate')

Manually readjust the modal’s position if the height of a modal changes while it is open (i.e. in case a scrollbar appears).

$('#myModal').modal('handleUpdate')

.modal('dispose')

Destroys an element’s modal.

Events

Bootstrap’s modal class exposes a few events for hooking into modal functionality. All modal events are fired at the modal itself (i.e. at the **). Type Description

|----------------|--------------------------------------------------------------|
| Event Type     | Description                                                  |
|----------------|--------------------------------------------------------------|
| show.bs.modal  | This event fires immediately when the **show** instance      |
|                | method is called. If caused by a click, the clicked element  |
|                | is available as the **relatedTarget** property of the event. | 
|                |                                                              |
| shown.bs.modal | This event is fired when the modal has been made visible to  |
|                | the user (will wait for CSS transitions to complete). If     |
|                | caused by a click, the clicked element is available as the   | 
|                | **relatedTarget** property of the event.                     |
|                |                                                              |
| hide.bs.modal  | This event is fired immediately when the **hide** instance   |
|                | method has been called.                                      |
|                |                                                              |
| hidden.bs.modal| This event is fired when the modal has finished being hidden |
|                | from the user (will wait for CSS transitions to complete).   |
|----------------|--------------------------------------------------------------|

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})
Oversupply answered 29/3, 2020 at 11:17 Comment(0)
I
10

My five cents on this one is that I don't want to have to target the bootstrap modal with an id and seeing as there should be only one modal at a time the following should be quite sufficient to remove the modal as toggle could be dangerous:

$('.modal').removeClass('show');
Indeliberate answered 11/8, 2015 at 9:26 Comment(2)
The intentions are good, but this approach won't always work. Other page elements, including <body>, have classes added to them that would have to be reverted as well. The best answer is to use the 'hide' method.Narcosis
you can define id to the element, but the problem is that the blur background remains constant. i resolved using this $('.modal-backdrop').remove()Griego
M
7

In some circumstances typing error could be the culprit. For instance, make sure you have:

data-dismiss="modal"

and not

data-dissmiss="modal"

Notice the double "ss" in the second example that will cause the Close button that fail.

Marciamarciano answered 13/8, 2016 at 9:48 Comment(0)
G
6

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(window).load(function(){
      $('#myModal').modal('show');
});
$(function () {
   $('#modal').modal('toggle');
});
</script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
  
</div>

</body>
</html>
Glade answered 20/7, 2016 at 9:54 Comment(3)
Error: "message": "Uncaught TypeError: $(...).modal is not a function"Philbo
Yes. I have the error if "Run code snippet" in Chrome (Linux Mint). But it works in Firefox.Philbo
@Ivan Burlutskiy, Thank u for informing me, These is a issue with jquery include, so i fixed it. now it works fine in all browsers.Glade
L
6

$('.modal.in').modal('hide');

use the above code to hide the backdrop of modal if you are using multiple modal pop in one page.

Lesser answered 16/5, 2017 at 16:41 Comment(1)
Or only $('.modal').modal('hide'); will do.Morello
V
6

We can close the modal pop-up in the following ways:

// We use data-dismiss property of modal-up in html to close the modal-up,such as

<div class='modal-footer'><button type='button' class="btn btn-default" data-dismiss='modal'>Close</button></div>

 // We can close the modal pop-up through java script, such as

 <div class='modal fade pageModal'  id='openModal' tabindex='-1' data-keyboard='false' data-backdrop='static'>

    $('#openModal').modal('hide'); //Using modal pop-up Id.
    $('.pageModal').modal('hide'); //Using class that is defined in modal html.
Vibes answered 5/6, 2017 at 8:19 Comment(0)
T
6
   function Delete(){
       var id = $("#dgetid").val();
       debugger
       $.ajax({
           type: "POST",
           url: "Add_NewProduct.aspx/DeleteData",
           data: "{id:'" + id + "'}",
           datatype: "json",
           contentType: "application/json; charset=utf-8",
           success: function (result) {
               if (result.d == 1) {
                   bindData();
                   setTimeout(function(){ $('#DeleteModal').modal('hide');},1000);
               }
           }
       });
   };
Thibodeaux answered 9/7, 2018 at 11:10 Comment(1)
Hi - thanks for your answer. I've formatted this as code (which was fairly simple - just indent the first line a bit more). However I'd guess that only the $('#DeleteModal').modal('hide'); is relevant here?Saylor
Y
5

I closed modal Programmatically with this trick

Add a button in modal with data-dismiss="modal" and hide the button with display: none. Here is how it will look like

<div class="modal fade" id="addNewPaymentMethod" role="dialog">
  <div class="modal-dialog">
   .
   .
   .
   <button type="button" id="close-modal" data-dismiss="modal" style="display: none">Close</button>
  </div>
</div>

Now when you want to close modal Programmatically just trigger a click event on that button, which is not visible to user

In Javascript you can trigger click on that button like this:

document.getElementById('close-modal').click();
Yerkovich answered 30/8, 2018 at 12:19 Comment(0)
B
5

After some test, I found that for bootstrap modal need to wait for some time before executing the $(.modal).modal('hide') after executing $(.modal).modal('show'). And i found in my case i need at least 500 milisecond interval between the two.
So this is my test case and solution:

$('.modal-loading').modal('show');
setTimeout(function() {
  $('.modal-loading').modal('hide');
}, 500);
Brennen answered 21/12, 2019 at 5:24 Comment(1)
this solves the issues I had with the modal not closing as I open another one, thanksWindsor
R
4

you can use;

$('#' + $('.modal.show').attr('id')).modal('hide');
Rodi answered 5/4, 2018 at 12:53 Comment(0)
T
4

In my case, I used a button to show the modal

<button type="button" class="btn btn-success" style="color:white"
    data-toggle="modal" data-target="#my-modal-to-show" >
    <i class="fas fa-plus"></i> Call MODAL
</button>

So in my code, to close the modal (that has the id = 'my-modal-to-show') I call that function (in Angular typescript):

closeById(modalId: string) {
  $(modalId).modal('toggle');
  $(modalId+ ' .close').click();
}

If I call $(modalId).modal('hide') it does't work and I don't know why

PS.: in my modal I coded that button element with .close class too

<button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
    <span aria-hidden="true">&times;</span>
</button>
Triptolemus answered 27/2, 2019 at 12:36 Comment(0)
S
4

This works for me. I'm a newbie so, Please ignore my usage of JQuery and Vanilla JavaScript together.

document.addEventListener("click",function(){
        $(".modal").modal('hide');
        });
Stockholder answered 20/9, 2021 at 6:31 Comment(0)
A
3

Using modal.hide would only hide the modal. If you are using overlay underneath the modal, it would still be there. use click call to actually close the modal and remove the overlay.

$("#modalID .close").click()
Anton answered 22/2, 2017 at 22:39 Comment(0)
B
3

Another way of doing this is that first you remove the class modal-open, which closes the modal. Then you remove the class modal-backdrop that removes the grayish cover of the modal.

Following code can be used:

$('body').removeClass('modal-open')
$('.modal-backdrop').remove()  
Bashemath answered 30/5, 2017 at 15:26 Comment(2)
Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include clarification, context and try to mention any limitations, assumptions or simplifications in your answer.Selmaselman
OK, so basically what this does is removes the class modal-open, which closes the modal. then removes the class modal-backdrop that removes the grayish cover of the modalBashemath
T
2

This code worked perfectly for me to close a modal (i'm using bootstrap 3.3)

$('#myModal').removeClass('in')
Tabathatabb answered 13/3, 2018 at 17:31 Comment(0)
I
2

In my case, main page from where bootstrap modal was triggered started to not responding after using $("#modal").modal('toggle'); way, but started responding in the following way:

$("#submitBtn").on("click",function(){
  $("#submitBtn").attr("data-dismiss","modal");
});
Ibnsina answered 29/3, 2018 at 10:16 Comment(0)
E
2

This works well

$(function () {
   $('#modal').modal('toggle');
});

However, when you have multiple modals stacking on top one another it is not effective, so instead , this works

data-dismiss="modal"
Entree answered 19/11, 2018 at 13:11 Comment(0)
L
2

Just add this in modal

div tabindex="-1"
Lynxeyed answered 7/7, 2020 at 11:39 Comment(0)
S
2

try this

 $('#yourmodal').click(); 
Swithin answered 8/7, 2022 at 17:29 Comment(0)
V
1

Besides, you can "click" on a 'x', that closes dialog. E.g.:

$(".ui-dialog-titlebar-close").click();

Veroniqueverras answered 10/1, 2017 at 21:10 Comment(0)
S
1

some times the solution up doesn't work so you d have properly to remove the in class and add the css display:none manually .

$("#modal").removeClass("in");
$("#modal").css("display","none");
Spooner answered 11/4, 2019 at 16:22 Comment(0)
S
1

my answer is not strictly related to question like many others above. But these conversations helped me to figure out why my bootstrap modal doesn't react when I click on a very general close button while it still closed it when I pressed the ESC button.

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

It might help someone.

If you put into your code (in some special cases it makes sense):

$modal.off('click')

then it also results that the modal won't be closed because the event is blocked.

In that case you have to handle it yourself:

$modal
  .on('click', '[data-dismiss="modal"]', function() {
      $modal.modal('hide');
  });
Slurry answered 17/12, 2021 at 15:55 Comment(1)
thank you, this works for me. data-dismiss='modal' aria-hidden='true'Superordinate
M
1

you can try with this just add

div tabindex="-1"

in your HTML and in jquery you can use

$('#myModal').modal('hide')

OR

$('#myModal').modal('toggle')
Mcentire answered 14/6, 2022 at 6:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.