280

I am using the Twitter bootstrap Modal dialog. When I click on the submit button of the bootstrap modal dialog, it sends an AJAX request. My problem is that the modal-backdrop doesn't disappear. The Modal dialog does disappear correctly, but instead "modal-backdrop in" that creates the opacity on the screen remain

What can I do?

lanoxx
  • 12,249
  • 13
  • 87
  • 142
paganotti
  • 5,591
  • 8
  • 37
  • 49
  • 5
    Are you using `$('#myModal').modal('hide')`? Can you put some code here? – Pigueiras Jul 17 '12 at 11:38
  • 20
    If you are using a copy and paste from the getboostrap site itself into an html generated selector, make sure you remove the comment ''. Bootstrap gets confused and thinks that the comment is a second modal element. It creates another back drop for this "second" element. – Jordan Jun 09 '15 at 19:50
  • @Jordan: Your comment needs to be an answer! In my case your comment was the correct solution! – BlaM Jun 15 '15 at 11:19
  • Refer the following: http://stackoverflow.com/questions/22207377/disable-click-outside-of-bootstrap-model-area-to-close-modal – Nutan Aug 27 '15 at 12:07
  • I know the question is old, but today I has a similar problem, in my situation there was a miss-removal of the class "modal-lg" that was left just to "modal" creating mess when you where going to close the modal witht he keyboard/click somewhere outside. – Matteo Jan 20 '16 at 09:00

38 Answers38

595

Make sure you're not replacing the container containing the actual modal window when you're doing the AJAX request, because Bootstrap will not be able to find a reference to it when you try to close it. In your Ajax complete handler remove the modal and then replace the data.

If that doesn't work you can always force it to go away by doing the following:

$('#your-modal-id').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
ChezFre
  • 6,502
  • 1
  • 19
  • 25
  • 2
    You can usually fix this problem be resequencing the flow of the javascript methods, possibly in conjunction w/ the modal "hidden" event. It's better to try that than a "hack" if you're coding with a team because there's less to get tripped up on when you return to the code at a later date. – Stone Oct 12 '12 at 18:30
  • 2
    I am using bootstrap 3.0 RC 1 and this problem still persists. I am not doing anything in case of hide/hidden event but this issue is still there and above hack works for me... – techgyani Aug 05 '13 at 07:07
  • 9
    Hiding the modal before the AJAX call is a poor solution if you need to evaluate the AJAX response and update the modal accordingly. – asciimo Oct 17 '13 at 01:32
  • I've tried most if not all of the suggestions here and from other threads. The only one that worked in my specific case was the one from this answer. (I mean the script not hiding before the java script, which I also think is not a good idea) Definitely a +1 – Ben Junior Apr 08 '14 at 21:32
  • I edited the answer to reflect the concerns expressed by some of you in the comments. I hope this will better reflect what's causing the issue and the flow of actions you should take to resolve it. – ChezFre Apr 10 '14 at 06:52
  • 21
    I believe this can also be caused by calling modal('hide') before the fade animation has fully completed. Removing the fade class from the modal may help. – EvilPuppetMaster Jul 09 '14 at 13:10
  • Not working for me... does this depend on a certain HTML page hierarchy? Also, I don't have a `modal-open` or `modal-backdrop` anywhere. – CodyBugstein Jul 22 '14 at 13:47
  • 7
    $('.modal-backdrop').remove(); resolved it for me, no need to remove fade class – Omar Aug 27 '14 at 18:16
  • Thanks alot! I was (via some obscure path) removing the overlaying element where the backdrop was and experienced the problem described. I moved the modal and backdrop so it is not removed from DOM anymore and works well! – Alexander Olsson Aug 28 '14 at 15:41
  • 3
    Actually I did it with `$('.modal-backdrop').fadeOut(150);` so it looks better, thanks! – ParPar Jul 06 '15 at 09:14
  • 2
    For the first line, `$('.modal').modal('hide');` will work too instead of `$('#your-modal-id').modal('hide');`, you don't need its id. – Dennis Hackethal Aug 14 '15 at 00:05
  • Best suggestion, I also applied it into my solution and it worked perfectly. – julia Oct 16 '15 at 18:56
  • 1
    If have to open one modal from opened modal. Then this way all backdrop will be lost. Can we specify backdrop to be lost for particular modal. ?? – Parveen Verma Nov 05 '15 at 09:02
  • 4
    Make sure you include $('body').removeClass('modal-open'); Otherwise; the background content(which I update by ajax, after modal done its job) does not show the scrollbars for large data that requires scroll down. – freewill Dec 06 '15 at 23:46
  • this is bug, when I open > use this function > open again the modal = result: no more modal – Storm Spirit Dec 08 '15 at 16:42
  • 45
    `$('.modal-backdrop').remove()` seems to break future modals opening properly. – krock Dec 10 '15 at 02:19
  • i am executing modal on a tag can u help me that – DAOdAppDev Feb 06 '16 at 14:46
  • @krock I have the same problem as you. I tried this solution but it when I try to open another modal it disappears in a split second after. Have you found any solution? – Cronas De Se Mar 08 '16 at 11:13
  • 5
    @CronasDeSe my problem was caused by bootstrap being loaded multiple times (multiple html fragments ajaxed in with bootstrap js dependency via an asset pipeline), so the elements had duplicate bootstrap events. When I removed the bootstrap dependency from the page fragments the problem went away. – krock Mar 09 '16 at 01:17
  • Yes this hides modal another problem is to open the modal user need to click twice – Veshraj Joshi Mar 06 '17 at 04:13
  • This method removes the modal-backdrop forcefully. But the modal remains hidden always. When I click to open the modal again only the backdrop is visible. Please help me. – monisha Sep 28 '17 at 11:29
  • This works but now I have to click my button twice after the hide to get the modal to open again. – Sam Mar 27 '18 at 17:46
  • @krock i've found another solution. you can find it in comments – Rez May 02 '18 at 12:43
  • Yep, I already had a partial view for the dialog and needed to update a dropdown within it so why not replace the whole dialog? Guess I'll just replace the dropdown part. – William T. Mallard Aug 18 '19 at 08:26
  • 2
    @krock please consider posting this as an answer. It solved the issue for me. – Jade Steffen May 20 '21 at 15:35
  • I had a multiple modals opened in the same time, so this did not worked for me. I succeeded to fix it with this: $('.modal-backdrop').last().css("display","none"); – Dacili Dec 30 '21 at 12:35
67

Make sure that your initial call to $.modal() to apply the modal behavior is not passing in more elements than you intended. If this happens, it will end up creating a modal instance, complete with backdrop element, for EACH element in the collection. Consequently, it might look like the backdrop has been left behind, when actually you're looking at one of the duplicates.

In my case, I was attempting to create the modal content on-the-fly with some code like this:

myModal = $('<div class="modal">...lots of HTML content here...</div><!-- end modal -->');
$('body').append(myModal);
myModal.modal();

Here, the HTML comment after the closing </div> tag meant that myModal was actually a jQuery collection of two elements - the div, and the comment. Both of them were dutifully turned into modals, each with its own backdrop element. Of course, the modal made out of the comment was invisible apart from the backdrop, so when I closed the real modal (the div) it looked like the background was left behind.

gasman
  • 23,691
  • 1
  • 38
  • 56
52

I just spent way too long on this problem :)

While the other answers provided are helpful and valid, it seemed a little messy to me to effectively recreate the modal hiding functionality from Bootstrap, so I found a cleaner solution.

The problem is that there are a chain of events that happen when you call

$("#myModal").modal('hide');
functionThatEndsUpDestroyingTheDOM()

When you then replace a bunch of HTML as the result of the AJAX request, the modal-hiding events don't finish. However, Bootstrap triggers an event when everything is finished, and you can hook into that like so:

$("#myModal").modal('hide').on('hidden.bs.modal', functionThatEndsUpDestroyingTheDOM);

Hope this is helpful!

Doug Moscrop
  • 4,479
  • 3
  • 26
  • 46
Bill Huertas
  • 746
  • 5
  • 9
  • 15
    I spent too long too! This answer gave me the clue - something was clobbering my DOM (angular). Looking at the bootstrap code, you can just force an immediate removal of the background by doing removing the fade class first: ```$('#myModal').removeClass('fade');$(myModal').modal('hide')'``` – Ross R Mar 21 '14 at 12:24
  • The should be the accepted answer - it uses the bootstrap API as intended and doesn't hack the body with .modal-open – Aaron Hudon Aug 04 '17 at 23:37
  • This is the most diligent and conscientious answer. – JacobIRR Dec 01 '17 at 18:10
  • Great answer, my problem was also due to an ajax call replacing the dom - I guess modal('hide') returns itself or the modal reference so we can attach to 'hidden.bs.modal' ? – Michael Harper Feb 18 '18 at 10:55
  • the statement *the modal-hiding events don't finish* gave me the idea on how to start my work around – SamuelDev Jul 24 '18 at 15:17
  • 2020 and still tripping over this one, in my case i cloned the original modal, so that i could reset it back to the original state, and the reset was happening before it was completely hidden. – DarkMukke Jun 06 '20 at 09:03
40

Insert in your action button this:

data-backdrop="false"

and

data-dismiss="modal" 

example:

<button type="button" class="btn btn-default" data-dismiss="modal">Done</button>

<button type="button" class="btn btn-danger danger" data-dismiss="modal" data-backdrop="false">Action</button>

if you enter this data-attr the .modal-backdrop will not appear. documentation about it at this link :http://getbootstrap.com/javascript/#modals-usage

kampageddon
  • 1,409
  • 15
  • 13
  • 2
    This is a true answer. Under no circumstance try to manually do the stuff Bootstrap's intended to do. If that would be your solution you're implementing it wrong. I think the boilerplate HTML on the bootstrap site is a little incomplete and that's why many people are experiencing the described behavior (incl. me). Thanks! +1 – Ben Fransen Mar 06 '16 at 19:34
  • 3
    What if you want trigger the modal not from a button? – shinzou Oct 24 '16 at 21:43
  • 9
    @ben you're wrong. `data-backdrop="false"` is simply an option telling bootstrap **not to use a backdrop at all**. This has nothing to do with the actual problem, it just avoids it. It'd be like saying "I cant swim so I stopped getting in the pool". That's cool, but you still cant swim and if you're boss throws you in the deep end, you'll drown. There are many cases where manual intervention is required, like when Angular stomps on the DOM in the background of your app. – Wesley Smith May 01 '17 at 23:00
  • This data-dismiss=modal is what helped me! The accepted answer does not allow you to show another modal again, it seems to be broken afterwards – Jay Aug 21 '20 at 19:03
  • Thank you, i really don't want to write js just for a single modal. In my opinion this should be on top. – Jp Silver Jul 02 '21 at 01:37
27

I know this is a very old post but this might help. This is a very small workaround by me

$('#myModal').trigger('click');

Thats it, This should solve the issue

20

If you are using a copy and paste from the getboostrap site itself into an html generated selector, make sure you remove the comment '<!-- /.modal -->'. Bootstrap gets confused and thinks that the comment is a second modal element. It creates another back drop for this "second" element.

BlaM
  • 28,465
  • 32
  • 91
  • 105
Jordan
  • 9,642
  • 10
  • 71
  • 141
  • I'll be damned...this was exactly my problem. Removed the comment and it worked. How the hell does an HTML comment trip up Bootstrap!? – Turner Hayes Jul 05 '15 at 19:54
  • I believe it is looking for html elements to get a count. Since comments are considered elements this count is wrong with that comment in place. – Jordan Jul 06 '15 at 18:40
  • happened to me while had this file in Mustache template – Pavel 'PK' Kaminsky Aug 19 '15 at 22:27
  • Comments exist in the DOM in such a way that it confused the javascript half of the modal component. I forget how exactly. This was a while ago. – Jordan Jan 01 '16 at 00:23
  • Holy Moley - that actually works! That's such a weird bug. – Dror S. Jun 28 '17 at 13:42
  • I think they fixed this a while ago because I didn't experience with BS3 or BS5.0. But when I upgraded to 5.1, I had this issue and your solution worked. – carlin.scott Oct 01 '21 at 00:30
10

.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).

So instead of

$('#myModal').modal('hide');
$('#someOtherSelector').trigger('click');

do

$('#myModal').modal('hide');
$('#myModal').on('hidden.bs.modal', function() {
   $('#someOtherSelector').trigger('click');
});

So you are sure to wait till the "hide" event is finished.

Helmut
  • 426
  • 3
  • 14
  • This is definitely a better solution. This way you dont have to mess with the modal classes which is probably the more correct way to fix this issue. – DeanMWake May 06 '16 at 13:21
9

I suffered a similar issue: in my modal window, I have two buttons, "Cancel" and "OK". Originally, both buttons would close the modal window by invoking $('#myModal').modal('hide') (with "OK" previously executing some code) and the scenario would be the following:

  1. Open the modal window
  2. Do some operations, then click on "OK" do validate them and close the modal
  3. Open the modal again and dismiss by clicking on "Cancel"
  4. Re-open the modal, click again on "Cancel" ==> the backdrop is no longer accessible!

well, my fellow next desk saved my day: instead of invoking $('#myModal').modal('hide'), give your buttons the attribute data-dismiss="modal" and add a "click" event to your "Submit" button. In my problem, the HTML (well, TWIG) code for the button is:

<button id="modal-btn-ok" class="btn" data-dismiss="modal">OK</button>
<button id="modal-btn-cancel" class="btn" data-dismiss="modal">Cancel</button>

and in my JavaScript code, I have:

$("#modal-btn-ok").one("click", null, null, function(){
    // My stuff to be done
});

while no "click" event is attributed to the "Cancel" button. The modal now closes properly and lets me play again with the "normal" page. It actually seems that the data-dismiss="modal" should be the only way to indicate that a button (or whatever DOM element) should close a Bootstrap modal. The .modal('hide') method seems to behave in a not quite controllable way.

Hope this helps!

Dima Gabachov
  • 91
  • 1
  • 2
9

This problem can also occur if you hide and then show again the modal window too rapidly. This was mentioned elsewhere for question, but I'll provide some more detail below.

The problem has to do with timing, and the fade transition. If you show a modal before the fade out transition for the previous modal is complete, you'll see this persistent backdrop problem (the modal backdrop will stay on the screen, in your way). Bootstrap explicitly does not support multiple simultaneous modals, but this seems to be a problem even if the modal you're hiding and the modal you're showing are the same.

If this is the correct reason for your problem, here are some options for mitigating the issue. Option #1 is a quick and easy test to determine if the fade transition timing is indeed the cause of your problem.

  1. Disable the Fade animation for the modal (remove the "fade" class from the dialog)
  2. Update the modal's text instead of hiding and re-showing it.
  3. Fix the timing so that it won't show the modal until it's finished hiding the previous modal. Use the modal's events to do this. http://getbootstrap.com/javascript/#modals-events

Here are some related bootstrap issue tracker posts. It is possible that there are more tracker posts than I've listed below.

Mark F Guerra
  • 892
  • 10
  • 13
7

Another possible mistake that could produce this problem,

Make sure you didn't included bootstrap.js script more than once in your page!

Positivity
  • 5,406
  • 6
  • 41
  • 61
5

Even I ran into a similar problem, I had the following two buttons

<button id="confirm-delete-btn" >Yes, Delete this note.</button>
<button id="confirm-delete-cancel" data-dismiss="modal">No</button>

I wanted to perform some ajax operation and on success of that ajax operation close the modal. So here is what I did.

$.ajax({
        url: '/ABC/Delete/' + self.model.get("Id")
            , type: 'DELETE'
            , success: function () {                    
                setTimeout(function () {
                    self.$("#confirm-delete-cancel").trigger("click");
                }, 1200);
            }
            , error: function () {}
        });

I triggered the click event of the 'No' button which had the data-dismiss="modal" property. And this worked :)

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • Manually triggering click event doesn't close the modal in IE9/IE10 for me. Trying to find a solution. – Antony Harder Mar 25 '14 at 14:17
  • Nevermind, the problem was a bit different - I had data-enable condition attached to that button, and though IE did proceed with onclick events, it didn't take into consideration data-dismiss attr. – Antony Harder Mar 25 '14 at 14:55
5

use:

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

Source

Jamshid Hashimi
  • 7,639
  • 2
  • 28
  • 27
4

$('#myModal').trigger('click');

This worked for me. Its not closing because when you open the popup it triggers 2 or 3 modal-backdrops. So when you do $('#myModal')).modal('hide'); it only effect one modal-backdrop and rest remains.

Ashhab
  • 199
  • 1
  • 5
3

This solution is for Ruby on Rails 3.x and a js.erb file that rebuilds part of the DOM including the modal. It works regardless if the ajax call came from the modal or from a different part of the page.

if ($("#my-modal").attr("aria-hidden") === "false") {
  $("#my-modal").modal('hide').on('hidden.bs.modal', function (event) {
    functionThatEndsUpDestroyingTheDOM();
  });
} else {
  functionThatEndsUpDestroyingTheDOM();
}

Thanks to @BillHuertas for the starting point.

mindriot
  • 14,149
  • 4
  • 29
  • 40
3

Adding data-dismiss="modal" on any buttons in my modal worked for me. I wanted my button to call a function with angular to fire an ajax call AND close the modal so I added a .toggle() within the function and it worked well. (In my case I used a bootstrap modal and used some angular, not an actual modal controller).

<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="functionName()"> Do Something </button>

$scope.functionName = function () {
angular.element('#modalId').toggle();
  $.ajax({ ajax call })
}
this.girish
  • 1,296
  • 14
  • 17
wendyg
  • 41
  • 6
3

After applying the top rated solution I've had a problem that it breaks future modals opening properly. I've found my solution which works good

        element.on("shown.bs.modal", function () {
            if ($(".modal-backdrop").length > 1) {
                $(".modal-backdrop").not(':first').remove();
            }
            element.css('display', 'block');
        });
Rez
  • 650
  • 7
  • 5
2

updatepanel issue.

My issue was due to the updatepanel placement. I had the entire modal in the updatepanel. If you declare the modal outside the updatepanel and just have say, the modal body, in the update panel, then the $('#myModalID').modal('hide'); worked.

Al Option
  • 601
  • 6
  • 5
  • This was my problem. I had an AjaxManager creating update panels around my usercontrol which contained the whole modal. I left only the modal's body in the usercontrol and moved everything in the main page and everything started working as expected, so don't ajaxify your
    part!
    – AlexanderD Oct 10 '17 at 13:39
2

Another point of view to this question. (I'm using the bootstrap.js version 3.3.6)

I mistaken initialize modal both by manually in javascript:

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

and by using

data-toggle="modal"

in this button like example below (shown in document)

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

so the result its create two instance of

<div class="modal-backdrop fade in"></div>

append to the body of my html when open the modal. This can be the cause when closing the modal by using function:

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

it remove only one backdrop instance (as show above) so the backdrop won't disappeared. But it did disappear if you use data-dismiss="modal" add on html as show in bootstrap doc.

So the solution to my problem is to only initialize modal manually in javascript and not using data attribute, In this way I can both close the modal manually and by using data-dismiss="modal" features.

Hope this will help if you encountered the same problem as me.

ohm89
  • 311
  • 1
  • 3
  • 12
2

FYI in case someone runs into this still... I've spent about 3 hours to discover that the best way to do it is as follows:

$("#my-modal").modal("hide");
$("#my-modal").hide();
$('.modal-backdrop').hide();
$("body").removeClass("modal-open");

That function to close the modal is very unintuitive.

Nick M
  • 2,424
  • 5
  • 34
  • 57
1

In .net MVC4 project I had the modal pop up (bootstrap 3.0) inside an Ajax.BeginForm( OnComplete = "addComplete" [extra code deleted]). Inside the "addComplete" javascript I had the following code. This solved my issue.

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

$("#moreLotDPModal").data('bs.modal').isShown = false;

$('body').removeClass('modal-open');

$('.modal-backdrop').remove();

$('#moreLotDPModal').removeClass("in");

$('#moreLotDPModal').attr('aria-hidden', "true");

Community
  • 1
  • 1
RasikaSam
  • 5,363
  • 6
  • 28
  • 36
1

I had the same problem. I discovered it was due to a conflict between Bootstrap and JQueryUI.

Both use the class "close". Changing the class in one or the other fixes this.

1

Using toggle instead of hide, solved my problem

Yash K
  • 41
  • 2
1

Make sure you are not using the same element Id / class elsewhere, for an element unrelated to the modal component.

That is.. if you are identifying your buttons which trigger the modal popups using the class name 'myModal', ensure that there are no unrelated elements having that same class name.

user2707674
  • 333
  • 1
  • 6
  • 14
1

for me, the best answer is this.

<body>
<!-- All other HTML -->
<div>
    ...
</div>

<!-- Modal -->
<div class="modal fade" id="myModal">
    ...
</div>

Modal Markup Placement Always try to place a modal's HTML code in a top-level position in your document to avoid other components affecting the modal's appearance and/or functionality.

from this SO answer

PurTahan
  • 789
  • 8
  • 24
1

I had the same problem when trying to submit the form. The solution was to change the button type from submit to button and then handle the button click event like so:

'click .js-save-modal' () {
    $('#myFormId').submit();
    $('#myModalId').modal('hide');
}
sym
  • 43
  • 5
0

I had this very same issue.

However I was using bootbox.js, so it could have been something to do with that.

Either way, I realised that the issue was being caused by having an element with the same class as it's parent. When one of these elements is used to bind a click function to display the modal, then the problem occurs.

i.e. this is what causes the problem:

<div class="myElement">
    <div class="myElement">
        Click here to show modal
    </div>
</div>

change it so that the element being clicked on doesn't have the same class as it's parent, any of it's children, or any other ancestors. It's probably good practice to do this in general when binding click functions.

Vin
  • 1,975
  • 5
  • 27
  • 34
0

I am working with Meteor and I just got the same problem. The cause of my bug was this:

{{#if tourmanager}}
    {{>contactInformation tourmanager}}
{{else}}
    <a href="#addArtistTourmanagerModal" data-toggle="modal"><i class="fa fa-plus"></i> Tourmanager toevoegen</a>
    {{>addArtistTourmanagerModal}}
{{/if}}

As you can see I added the modal in the else, so when my modal updated the contactinformation the if had another state. This caused the modal template to be left out of the DOM just before it would close.

The solution: move the modal out of the if-else:

{{#if tourmanager}}
    {{>contactInformation tourmanager}}
{{else}}
    <a href="#addArtistTourmanagerModal" data-toggle="modal"><i class="fa fa-plus"></i> Tourmanager toevoegen</a>
    {{>addArtistTourmanagerModal}}
{{/if}}
Scuba Kay
  • 2,004
  • 3
  • 26
  • 48
0
//Create modal appending on body
myModalBackup = null;
$('#myModal').on('hidden.bs.modal', function(){
       $('body').append(myModalBackup.clone());
    myModalBackup = null;
});

//Destroy, clone and show modal
myModalBackup = $('#myModal').clone();
myModalBackup.find('.modal-backdrop').remove();
$('#myModal').modal('hide').remove();
myModalBackup.find('.info1').html('customize element <b>1</b>...');
myModalBackup.find('.info2').html('customize element <b>2</b>...');                             
myModalBackup.modal('show');

fiddle --> https://jsfiddle.net/o6th7t1x/4/

Fábio Zangirolami
  • 1,856
  • 4
  • 18
  • 33
0

the initial value of your data-backdrop attribute can be

"static","true", "false" .

static and true add the modal shadow, while false disable the shadow, so you just need to change this value with the first click to false . like this:

$(document).on('ready',function(){
 
 var count=0;
 
$('#id-which-triggers-modal').on('click',function(){
  
  if(count>0){
  
   $(this).attr('data-backdrop','false')
  }
  count++;
});


});
0

I had the modal backdrop screen freeze problem but in a slightly different scenario: When 2 back to back modals were being displayed. e.g. The first would ask for confirmation to do something and after the 'confirm' button was clicked, the action would come across an error and the 2nd modal was going to be displayed to popup the error message. The 2nd modal backdrop would freeze the screen. There were no clashes in class names or id's of the elements.

The way the problem was fixed was to give the browser enough time to deal with the modal backdrop. Instead of immediately taking the action after the 'confirm' was clicked, give the browser say 500ms to hide the 1st modal and clean up the backdrop etc - then take the action which would end up in showing the error modal.

<button type="button" class="btn btn-red" data-dismiss="modal" on-tap="_dialogConfirmed">Confirm</button>
...

The _dialogConfirmed() function has the following code:

    var that = this;

    setTimeout(function () {
      if (that.confirmAction) {
        (that.confirmAction)();
        that.confirmAction = undefined;
      }
    }, 500);

I'm guessing the other solutions worked because they took enough extra time giving the browser the needed cleanup time.

user6317928
  • 495
  • 4
  • 4
0

In ASP.NET, add an update for UpdatePanel on code behind after the jquery command. Example:

    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal('hide');", true);
    upModal.Update();
mathias.horn
  • 241
  • 1
  • 8
  • 12
0

From https://github.com/twbs/bootstrap/issues/19385

Modal's show/hide methods are asynchronous. Therefore, code such as:

foo.modal("hide"); bar.modal("show"); is invalid. You need to wait for the showing/hiding to actually complete (by listening for the shown/hidden events; see http://getbootstrap.com/javascript/#modals-events ) before calling the show or hide methods again.

I had this problem when I opened the same modal twice too fast, so an easy fix was checking if it was already shown, then to not show it again:

$('#modalTitle').text(...);
$('#modalMessage').text(...);
if($('#messageModal').is(':hidden')){
    $('#messageModal').modal('show');
}
shinzou
  • 5,850
  • 10
  • 60
  • 124
0

Try this

$('#something_clickable').on('click', function () {
  $("#my_modal").modal("hide");
  $("body").removeClass("modal-open");
  $('.modal-backdrop').remove();
 });

It works fine for me.

A H K
  • 1,758
  • 17
  • 29
0

I had a similar problem. I was using Boostrap in conjunction with Backbone, and I was capturing clicks of the "Do it" button, and then stopping propagation of those events. Bizarrely, this made the modal go away, but not the background. If I call event.preventDefault() but do not call stopPropagation(), it all works fine.

gischer
  • 274
  • 1
  • 3
  • 8
0

This Line of Code after many search solved my problem, that i wanted to close the modal on ajax success:

$('#exampleModal').modal('hide');
$("[data-dismiss=modal]").trigger({ type: "click" });

Many thanks, Manuel Fernando https://stackoverflow.com/a/27218322/5935763

0

Recently I had this problem and none of solutions provided here helped me. Or it completely destroyed it so it could not be shown again. On document ready also did not work but what worked is that I wrapped all my listeners with immediately invoked function like this:

$(function () {
    $('#btn-show-modal').click(function () {
        $("#modal-lightbox").modal('show');
    });

    $('#btn-close-modal').click(function () {
        $("#modal-lightbox").modal('hide');
    });
});
N. Djokic
  • 898
  • 1
  • 6
  • 19
0

There are cases where the other answers (helpful and valid) cannot be easily applied. Then a possible workaround is to implement an event that triggers a click on the modal-backdrop shortly after the modal dialog disappears.

Here is an example based on the following modal dialog:

<div class="modal fade ..." id="IdOfMyModal" tabindex="-1" role="dialog" aria-labelledby="" aria-hidden="true">
...
</div>

To remove the "modal-backdrop in" (that creates the background opacity on the screen) on clicking the modal, add the following code:

$('#IdOfMyModal').on("click", function() {
    setTimeout(function() {
        if ($('#IdOfMyModal').css("opacity") != "1")
            $('.modal-backdrop').trigger('click');
    }, 100);
});
ircama
  • 75
  • 1
  • 5
0

After going through all the answers I came up with a catch-all solution. Eventually this is the only thing that worked for me. (vanilla javascript):

            var elem = document.querySelectorAll('[data-dismiss="modal"]')[0];
            var evt = new Event('click');
            elem.dispatchEvent(evt);

            var modalelem = document.getElementById('exampleModalCenter');

            var myModal = new bootstrap.Modal(modalelem, { keyboard: false })

            const fade = modalelem.classList.contains('fade');
            if (fade) {
                modalelem.classList.remove('fade');
            }

            myModal.hide();
            myModal.dispose();

            var backdrop = document.getElementsByClassName('modal-backdrop')[0];
            backdrop.style.display = 'none';

            var modalopen = document.getElementsByClassName('modal-open')[0];
            modalopen.classList.remove('modal-open');
            modalopen.style.removeProperty("overflow");\
Sagi
  • 981
  • 11
  • 15