Bootstrap close modal not working
Asked Answered
W

25

75

I have two button here that are being used to close the modal. The first is the close icon and the other one is cancel button, both use data-dismiss to close the modal. However, both of them are not working. I am using the same code for another modal and there they are working fine. Any guesses?

<div id="timeSelectModal{{entry.position - 1}}" style="display: none" class="modal">
    <div class="modal-dialog">
        <div id="timeSelectModalContent" class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <label>
                <input id="checkbox8pm{{entry.position - 1}}" type="checkbox" value="first_checkbox">
                <label class="checkbox-label">Thursday, 08:00 pm.</label>
            </label>
            <br>
            <label>
                <input id="checkbox9pm{{entry.position - 1}}" type="checkbox" value="second_checkbox">
                <label class="checkbox-label">Thursday, 09:30 pm.</label>
            </label>
            <div id="time-modal-footer" class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="timeSaveButton{{entry.position - 1}}" v-on:click="setTime(entry.position - 1)">Save</button>
            </div>
        </div>
    </div>
</div>
Wagonlit answered 23/7, 2016 at 2:47 Comment(2)
This is old but did you try removing ` style="display: none"`? It turns out that using that instead of Bootstrap's classes/methods for showing and hiding can cause things to break.Jotting
this thread is old but when ever I faced this issue, it was a matter of giving z-index to the "X" button.Tisza
L
175

I was stuck on this for a while also. I have no idea why but when I used data-bs-dismiss in stead of data-dismiss in the class for the close button it worked for me.

data-dismiss is on Bootstrap 4.x version while data-bs-dismiss is on Bootstrap 5.x version.

Please see below full code for close button.

<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
Liquorice answered 19/1, 2021 at 20:36 Comment(8)
I think you meant to paste in some code instead of just the word Close :)Divisibility
This worked for me! The code for the button should be: <button id='closeModal' type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>Catercorner
Thanks... forgot, BS5 requires the 'bs-'Olson
Thanks ,worked for me ,Firry
Worked for me as well. Should we do the same for data-save? change it to data-bs-save?Looney
At least for me data-dismiss worked in Bootstrap 4 but was not with Bootstrap 5. Changing it to data-bs-dismiss for Bootstrap 5 did the trick.Worship
can anyone explain why this method works? also thanks for answer it worked.Scoria
This seems to be a problem when you use different js libraries, that also use the data attribute. Standard in Bootstrap 5 for every data-attribute starts with "data-bs" - but just the dismiss buttons are called with only "data" ... maybe this should be fixed for future versions for @bootstrapHeavyweight
S
88

remove the "fade" class.

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

change to

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

Fade is an effect, if you remove fade, your modal will not have fade effect. The several problem which cause this issue is not call modal with right method.

Wrong method : $("#myModal").show();

Right method : $("#myModal").modal('show');

Studio answered 5/6, 2019 at 13:12 Comment(3)
This was it! After hours tweaking the html and jQuery, it ended up being this class that was causing the issue!Groundsel
It worked for me as well but i am not understanding why it doesn't work with fade class put inisde the div. fade just gives a transition effect right?Sabah
This was it! I was calling show with the wrong methodBiffin
I
25

Very old topic but it still shows up first for people searching this problem, likely caused by them making the same simple mistake I did which was failing to ensure that the modal div was outside of the main body div from which it was launched. To use the Material Kit as an example, you should double check that the target "#myModal" div is outside the closing div tag for your main container.

<div class="main main-raised">
    <div class="container">
    <!--                 modals -->
        <div class="row" id="modals">
            <div class="col-md-6">
                <button class="btn btn-primary btn-raised btn-round" data-toggle="modal" data-target="#myModal">
                    Classic modal
                </button>
            </div>

        </div>
    <!--                 end modals              -->
    </div>
</div>

<!-- Classic Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    <i class="material-icons">clear</i>
                </button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
                <p>Hey hey</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-simple">Nice Button</button>
                <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<!--  End Modal -->
Insightful answered 19/3, 2017 at 2:49 Comment(3)
Thank you...Thank You...and THANK YOU. This has been driving me nuts for weeks. However, is there not a way to include the modal in "content container" where its to be deployed at? I broke my pages in "menus1.html" <containerPage.html> and "menus2.html and in every "containerPage.html" include menus1.html at the top of the page and include menus2.html at the bottomof the page so all my menus/dropdowns, page headers are contained ONCE in the two menus1/2 pages - makes management of my website 1000x fold easier - until I run into problems like the above modal issue.Bohrer
I tried a couple different ways to do exactly what you're looking for and could not get it to work, unfortunately. I'm not exactly an expert though so my failure probably shouldn't be taken as a sign it can't be done.Insightful
yeah, I haven't had any luck either. I applied custom z-index to the actual modal to be greater than the z-index that greys out the whole page - but that didn't work.Bohrer
D
21

SUMMARY OF BOOTSTRAP 5 ISSUE

Hi. Like everyone else this tripped me up. This thread has spanned a long period and certainly there have been other issues causing the problem. However, as Alexandre Elshobokshy has mentioned unwittingly, changing

data-bs-dismiss

instead of

data-dismiss

works. I wanted to call this out since it is correct but there are additional keys that need to be updated for Modals to work with Bootstrap and HTML 5.

HTML5 has changed the tags required by Bootstrap. One is the data-bs-dismiss.

The others are:

data-bs-toggle & data-bs-target

I hope this helps others !

Drinkable answered 25/10, 2021 at 10:53 Comment(0)
B
13

First check you have included bootstrap.js file in your html correctly.

You can try this code and replace the button tag for closing modal by -

<a href="#" class="close" data-dismiss="modal" aria-label="close">&times;</a>

If still doesn't work.. Let me know.!

You can add an on-click event on close button in jQuery. Like this-

$("#yourModal").modal("hide"); 
Bigham answered 23/7, 2016 at 4:2 Comment(4)
Didn't work. I am using the same two buttons in another modal in the same html file and they are working fine so it is definitely included. I'm just wondering if it has to do something with my modal definition.Wagonlit
Check it out now you can JavaScript for modal closingBigham
I certainly can. But the whole point of using that approach was to not use js code such as listeners.Wagonlit
Can't see why but when I open my modal by .modal("show"), data-dismiss="modal" is not enough to close the modal so I have to $("#mymodal .close").click(function(){$("#mymodal").hide();});Questor
S
8

What helped in mine case, I've replaced data-dismiss with data-bs-dismiss, now it works!

Scotopia answered 16/5, 2021 at 18:55 Comment(0)
A
4

Give ID 'modalClose' to Model's Close button and ID 'myView' to your Model,

then use the following code:

    <script>
    $(function () {
        $('#modalClose').on('click', function () {
            $('#myView').hide();
        })
    })

</script>

It will work like a charm.

Alburga answered 25/10, 2019 at 7:8 Comment(1)
it's better to use modal('hide') instead of hide()Brittain
V
3

Here is my implementation of a modal you can use for comparing to help troubleshoot what errors exist in your modal code.

<html lang="en">
<head>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<h2>click Here</h2>
<div class="container">
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
      <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>
Vermicide answered 23/7, 2016 at 4:12 Comment(6)
Use this <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>Vermicide
if still not working use this $('button[data-dismiss="modal"]').click(function(){ $(this).parent().parent().parent().parent().modal('hide'); })Nudge
An upvote, I have not noticed the rest of the code if it works or not however the css and js included files resolved my issue as I was missing the jquery file.Subsidiary
@Subsidiary Please upvote to this answer so that this answer may help to othersVermicide
@Mr.HK I have upvoted it already. If you had noticed earlier the counter was -1, on my upvote it is now 0. Better than -1 I suppose :-)Subsidiary
@Subsidiary Yes I did't notice, Thank you :-)Vermicide
W
3

In my case I had other div over it.
I'v solved with z-index.

.modal button.close {
    z-index: 1000;
}
Want answered 6/6, 2020 at 16:41 Comment(0)
K
3

in 2023 use

$('#mypopup').modal('show');

instead of

$('#mypopup').show();

either rises the popup w/o any issue . But that Cancel works with first one only

Kin answered 12/1, 2023 at 19:47 Comment(0)
T
2

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.

Territory answered 8/10, 2018 at 6:19 Comment(0)
M
2

I had this issue too and found this page so thought I would post my solution for anybody who may do the same.

Mine was down to the way the modal appeared. Somebody had use .toggle() when it should be .modal('show') so I guess from the modal point of view it never appeared properly so it can't disappear either.

Hope that helps somebody living in the future.

Mathematical answered 19/8, 2020 at 9:32 Comment(0)
A
2

I had the same issue. I fixed the problem adding "events.js" where inside i wrote this code:

$("button[data-dismiss=modal]").click(function()
{
  $(".modal").modal('hide');
});

By adding this code in each head of your page u will able to close modal by native buttons. I hope this solution can be helpful for someone

Application answered 29/7, 2021 at 11:58 Comment(1)
Upping this one as this was more useful to throw in a main JS file, rather than having to add any of the other suggestions to separate html files.Mesocratic
F
2

it happens when you use bootstrap 5, the below code worked for me. I hope it will work for you.

<button type="button" class="close" data-bs-dismiss="modal">X</button>

Thanks

Foreglimpse answered 1/11, 2022 at 18:46 Comment(1)
I had the same issue, and this is the best answer who uses Bootrap 5, replace the data-dismiss to data-bs-dismiss.Norsworthy
H
1

If you are using bootstrap v5.x and opening and closing the modal programmatically, and it's still not working, it means there could be one or more reasons behind it. Few reasons are mentioned in other answers, but the problem I had is different. I spent lot of time to figure out the issue myself and adding the answer here, so that it might help someone who has similar issue like i had.

I had two methods for showing and closing the modals as below.

showModal(id) {
  const myModal = new bootstrap.Modal(document.getElementById(id));
  myModal.show();
}

hideModal(id) {
  const myModal = new bootstrap.Modal(document.getElementById(id));
  myModal.hide();
}

If we write methods like above and use it to close multiple modals dynamically by passing different modal IDs, then it may not work properly all the times, especially when you are dealing with multiple modals.

So what you have to do is modify the above-mentioned methods as below

showModal(id) {
  const myModal = bootstrap.Modal.getOrCreateInstance(document.getElementById(id));
  myModal.show();
}

hideModal(id) {
  const myModal = bootstrap.Modal.getOrCreateInstance(document.getElementById(id));
  myModal.hide();
}

So in old methods we were creating the instance of the modal multiple times with new boostrap, in the new methods we are using getOrCreateInstance method which will get the instance if already created or create a new instance if it doesn't exist.

Hamamelidaceous answered 11/10, 2023 at 12:43 Comment(1)
I am using Bootstrap 5.3 and this works :)Cetology
A
0

For me modal was not getting closed because script files had conflict somewere, so used minimum required script files to check the problem in closing model.Way I added scripts for which model was getting closed properly

"scripts": [
          "src/assets/js/lib/jquery/jquery.min.js",
          "src/assets/js/lib/bootstrap/js/popper.min.js",
          "src/assets/js/lib/bootstrap/js/bootstrap.min.js"
        ]

And for sure I had added bootstrap.min.css in styles.

Awlwort answered 2/11, 2018 at 9:54 Comment(0)
L
0

In my case I was missing the data-target attribute on the link that calls the modal.

<a href="#getResults"
   class="results-link"
   data-toggle="modal"
   data-target="#results-modal"
   data-providerName="${providerName}"
   data-individualID="${individualID}"
   data-reportID="@Model.ReportID">Results
</a>
Limb answered 31/5, 2020 at 20:49 Comment(0)
C
0

None of the answers helped me. But I was having issues as well.

I forgot to add the JavaScript file of Bootstrap. What I added was just the CSS of Bootstrap. Both the Bootstrap CSS and JS CDN links need to be added to the page.

So make sure you add this Bootstrap CDN to add the script:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
Chukker answered 27/8, 2021 at 8:59 Comment(0)
D
0

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

$modal.off('click')

then it also results that the modal won't be closed because the event is blocked. You can test it whether you can close the modal by pressing Esc. It that works then your click events are blocked.

You can debug it like this where you will see that it returns false:

$modal.on('click',function(event){
    console.log('debug click');
    console.log(event);
});

In that case you have to handle it yourself:

$modal
  .on('click', '[data-dismiss="modal"]', function() {
      $modal.modal('hide');
  });
Decompensation answered 17/12, 2021 at 16:3 Comment(0)
R
0

   const backdrops = document.querySelectorAll('.modal-backdrop.fade.show');
          Array.prototype.forEach.call(backdrops, function (node) {
            node.parentNode.removeChild(node);
          });
          $(`#${data.uniqueId}`).modal('hide');
          $(`#${data.uniqueId}`).parent().removeClass("open");
body {
  padding-right: 0 !important;
  overflow: auto !important;
}
Raney answered 23/2, 2022 at 2:25 Comment(1)
Please provide details what your solution does.Housel
S
0

I ran into this issue recently, all modals in my app acted correctly, but new one was 'mibehaving'. Anyway long story short, dont confuse

$("#flash-modal").modal('show');

with

$("#flash-modal").show();

show() is jQuery method changing css atribute display, you need to init it correctly with modal! Hope this helps someone...

Simonsen answered 31/7, 2022 at 10:23 Comment(0)
F
0

I was calling jQuery on target page. I noticed that when I removed this line, the close command worked.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Then I called the old version of jQuery and realized that it was working again.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

I don't know why it prevents the close button from working on 3.x and above..

Fading answered 19/9, 2022 at 16:59 Comment(0)
D
0

Have a look and ensure that you are not including the html data attributes to toggle the modal if you are handling the logic in javascript because this will cause the event to double fire, creating two modal-backdrop divs. This means that on hide/dismiss, it will remove 1 modal-backdrop but leaves the duplicate and hence it appears not to have closed.

On the event that presents the modal, have your dev tools open and look at the DOM, you will clearly see two .modal-backdrop divs are spawned.

Solution in this case is to choose between html data-attributes and JS logic, but not both.

Donalt answered 1/2, 2023 at 13:9 Comment(0)
R
0

In my case I modified the modal as per our design, So, I missed to include 'modal-content' class. After including, it worked.

Retiarius answered 31/5, 2023 at 11:34 Comment(0)
R
-2

use this code close model

<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="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<h2>click on button</h2>
<div class="container">
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
      <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>
Rue answered 23/7, 2016 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.