91

I'm very much a noob, so I think I'm overseeing something (probably obvious) with twitter bootstrap modal. What I am trying to do is get a modal to launch only on mobile. This works fine with adding the class .visible-phone on the modal div. So far so good. But then I want it to work, meaning you can close it with the X button. And I cannot get the button to work.

<div class="modal visible-phone" id="myModal">
  <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>text introductory<br>want to navigate to...</h3>
 </div>
 <div class="modal-body">
    <ul class="nav">
      <li> ... list of links here </li>
    </ul>
   </div>
  </div>

In the bottom of the html I put jquery.js (first) and bootstrap.modal.js and bootstrap.transition.js. Actually all of the bootstrap js modules (not to miss an include). I'm not experienced with js..

Please forgive me if I posed a really stupid Q. I could not find the answer to this specific situation in the log.

Monique De Haas
  • 1,031
  • 1
  • 7
  • 8

10 Answers10

219

$('#myModal').modal('hide') should do it

Nauphal
  • 6,194
  • 4
  • 27
  • 43
ayal gelles
  • 2,829
  • 1
  • 21
  • 18
  • yes, that's working. But I don't have the same animation we have using 'data-dismiss="modal"' ? – Chris Dec 26 '12 at 14:14
  • ok my mistake. Actually I don't remember the issue I had at the time, I now use this and it works perfectly. TY! – Chris Apr 21 '13 at 08:37
  • Learn more here .. http://stackoverflow.com/questions/10944302/twitter-bootstrap-how-to-close-modal-dialog – Sanjay Kumar Jul 19 '13 at 10:47
  • 6
    This is strange, `$('#myModal').modal('show')` works for me, but hide doesn't. – Belladonna Jul 30 '13 at 18:36
  • 3
    @LittleBigBot try using `$('#myModal').modal('toggle');` instead – Edson Horacio Junior Jul 06 '15 at 17:55
  • when I tested it in IE9 or older `$('#myModal').modal('hide');` did not work for me, but `$('#myModal').modal('toggle');` works well for all. – victorf Sep 02 '15 at 14:40
  • will this work with angular too considering angular is just javascript. I am sure this will not be the best angular way to achieve the result. – Kurkula Feb 17 '16 at 23:44
27

I had problems closing the bootstrap modal dialog, if it was opened with:

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

I solved this problem opening the dialog by the following link:

<a href="#myModal" data-toggle="modal">Open my dialog</a>

Do not forget the initialization:

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

I also used the following attributes for the closing button:

data-dismiss="modal" data-target="#myModal"
artkoenig
  • 7,117
  • 2
  • 40
  • 61
  • Hi artjom. Thnx! Will run it and give feedback. You are not using à button to open the modal? As that's what i am trying to achieve. Have à modal launch initially and only on mobile to offer à quick navigation menu to location (not relevant directly when on desktop) that's the idea. – Monique De Haas May 16 '12 at 17:37
  • Yes data-dismiss="modal" data-target="#myModal" solved my prob! appriciate! – Dheeraj Thedijje Dec 03 '15 at 17:09
13

Add the class hide to the modal

<!-- Modal Demo -->
<div class="modal hide" id ="myModal" aria-hidden="true" >

Javascript Code

 <!-- Use this to hide the modal necessary for loading and closing the modal-->
 <script>
     $(function(){
         $('#closeModal').click(function(){
              $('#myModal').modal('hide');
          });
      });
 </script>

 <!-- Use this to load the modal necessary for loading and closing the modal-->
 <script>
     $(function () {
         $('#myModal').modal('show');
     });
  </script>
shaunak1111
  • 951
  • 1
  • 11
  • 17
13

.modal('hide') manually hides a modal. Use following code to close your bootstrap model

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

Take a look at working codepen here

Or

Try here

$(function () {
    $(".custom-close").on('click', function() {
        $('#myModal').modal('hide');
    });
});
<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.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

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

<!-- 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">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        
          
          <a class="custom-close"> My Custom Close Link </a>
          
          
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
6

Try specifying exactly the modal that the button should close with data-target. So your button should look like the following -

<button class="close" data-dismiss="modal" data-target="#myModal">×</button>

Also, you should only need bootstrap.modal.js so you can safely remove the others.

Edit: if this doesn't work then remove the visible-phone class and test it on your PC browser instead of the phone. This will show whether you are getting javascript errors or if its a compatibility issue for example.

Edit: Demo code

<html>
<head>
    <title>Test</title>
    <link href="/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/bootstrap.modal.js" type="text/javascript"></script>

    <script type="text/javascript">
      $(document).ready(function () {
        if( navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
          ) {
          $("#myModal").modal("show");
        }

        $("#myModalClose").click(function () {
          $("#myModal").modal("hide");
        });
      });
    </script>
</head>
<body>
    <div class="modal hide" id="myModal">
      <div class="modal-header">
        <a class="close" id="myModalClose">×</a>
        <h3>text introductory<br>want to navigate to...</h3>
     </div>
     <div class="modal-body">
        <ul class="nav">
          <li> ... list of links here </li>
        </ul>
   </div>
  </div>
</body>
</html>
Simon Cunningham
  • 5,540
  • 1
  • 17
  • 7
  • Hi @Simon Cunningham Tnx a million for answering! I've put in the data-target. Did not work (unfortunately) Then I removed the visible-phone class. Did not make a difference. `code` `code` – Monique De Haas May 11 '12 at 08:34
  • `` – Monique De Haas May 11 '12 at 08:42
  • Sorry for the text mess up there ;) I followed your advice. Seems logical to give the close button an exact data-target. But somehow I'm still not getting it to work. Even if disabling visible phone. Does not seem to influence the close button. (which is kind of a good thing) – Monique De Haas May 11 '12 at 08:42
  • How are you initially opening your modal? Try opening it as below -Open modal – Simon Cunningham May 11 '12 at 08:57
  • I've added some cut down demo code to my original answer. The javascript and css files are local to my test project, just replace them with links to your own. – Simon Cunningham May 11 '12 at 09:01
  • Hi simon! what I am trying to achieve is a modal to open automatically (without button) when on mobile. To offer a quick navigation menu to location office or tel function. If you just want to get on the site when on mobile (not traveling to location), you can close the modal. So I want the modal without the button to open automatically when on screen size mobile, but with x to close. – Monique De Haas May 11 '12 at 09:19
  • Monique, rather than use a CSS class you'll need to use javascript to detect what device the user is using and then call the javascript to open the modal. I've added some more code to the answer above. – Simon Cunningham May 14 '12 at 08:46
  • Hi Simon, will use and test this with device central & devices, thnx. Just had a question beforehand. How will this mix in with my css media queries? I am building a responsive bootstrap design. (will test) – Monique De Haas May 14 '12 at 12:38
  • The only things you really need from my demo HTML are everything inside the head section and the two IDs given to the modal window (myModal) and the close button (myModalClose). So just make sure that the modal div is ID myModal and whatever button/link you use to close the modal is ID myModalClose. You can fit this into whatever HTML you are currently using without it affecting the responsiveness. – Simon Cunningham May 14 '12 at 14:27
  • Dear Simon,Thank you so much for hanging in there with me. I've installed all, with your JS-snippet in head. Seeing modal, still not able to close. So i'm doing something wrong in the initialization of the close function I guess.. But yr script just gives it 1 function; to hide upon close button..(I don't get it yet, what's wrong, looks oke..) – Monique De Haas May 15 '12 at 09:44
  • Monique, could you post the HTML from your page? You can take out any content as in your original post but do include the head and the div structure for your modal. Its probably to do with the ID of the close button, it needs to match the $("#myModalClose").click event handler in the javascript. All that javascript does is say "on the click of anything with an id of myModalClose" so make sure they match. – Simon Cunningham May 15 '12 at 11:17
  • Hi Simon, Posted the head and body code in an answer block here – Monique De Haas May 15 '12 at 12:56
  • That's strange, I've tested your code and it works on both my desktop machine and my iPad. – Simon Cunningham May 15 '12 at 13:46
  • it's not supposed to work on desktop and iPad. Only mobile. And then the issue is that the close button needs to get the modal hidden. I did see the modal (your first code)on all screens. Then I added class="visible-phone" to the modal and it only showed on narrow screens (css working) but still did not close... – Monique De Haas May 15 '12 at 14:17
  • What I would do is remove the if statement that checks for the useragent and remove the visible-phone class just for testing purposes. Get it working in a desktop browser as you have better debugging tools there. Once you see that the modal is working you should then start adding the mobile specific code and test it on the mobile. At the minute the problem could either be with JQuery, bootstrap modal or with the mobile code. – Simon Cunningham May 15 '12 at 15:19
  • Hi Simon. My internet connection flew off today... Kept me busy. Tommorow i will do as suggested and see of i can get it to work properly then ad mobile specific rules. then run some tests.thnx. – Monique De Haas May 16 '12 at 17:26
  • @SimonCunningham may i know from where `data-dismiss` property comes from ? m bit confused wanna clear something. – Pardeep Jain Feb 13 '16 at 06:30
6

According the documentaion hide / toggle should work. But it don't.

Here is how I did it

$('#modal-id').modal('toggle'); //Hide the modal dialog
$('.modal-backdrop').remove(); //Hide the backdrop
$("body").removeClass( "modal-open" ); //Put scroll back on the Body
user706001
  • 980
  • 7
  • 8
  • 1
    This is actually the correct "brute force" answer.. but i suggest to rewrite it to get the animation correct: `$("#modal-id").modal("toggle"); $(".modal-backdrop").fadeOut('fast',function(){ $("body").removeClass( "modal-open" ); $(".modal-backdrop").remove(); });` – DerDu Jan 02 '17 at 20:52
3

Try on this..

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

$('.modal-backdrop').remove();
animuson
  • 53,861
  • 28
  • 137
  • 147
Theek
  • 29
  • 1
2

I had the same problem in the iphone or desktop, didnt manage to close the dialog when pressing the close button.

i found out that The <button> tag defines a clickable button and is needed to specify the type attribute for a element as follow:

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

check the example code for bootstrap modals at : BootStrap javascript Page

Isma
  • 21
  • 4
0

If you have few modal shown simultaneously you can specify target modal for in-modal button with attributes data-toggle and data-target:

<div class="modal fade in" id="sendMessageModal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-sm">
           <div class="modal-content">
                <div class="modal-header text-center">
                     <h4 class="modal-title">Modal Title</h4>
                     <small>Modal Subtitle</small>
                </div>
                <div class="modal-body">
                     <p>Modal content text</p>
                </div>
                <div class="modal-footer">
                     <button type="button" class="btn btn-default pull-left" data-toggle="modal" data-target="#sendMessageModal">Close</button>
                     <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#sendMessageModal">Send</button>
                </div>
           </div>
      </div>
 </div>

Somewhere outside the modal code you can have another toggle button:

<a href="index.html#" class="btn btn-default btn-xs" data-toggle="modal" data-target="#sendMessageModal">Resend Message</a>

User can't click in-modal toggle button while these button hidden and it correct works with option "modal" for attribute data-toggle. This scheme works automagicaly!

Sound Blaster
  • 4,778
  • 1
  • 24
  • 32
0

Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh

I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:

HTML (modal footer):

 <div class="modal-footer form-footer"><br>
              <span class="caption">
                <button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart&nbsp; <i class="fa fa-shopping-cart"></i></button>     
                <button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel&nbsp; <i class="fa fa-close"></i></a>
              </span>
      </div>

jQUERY:

$(document).ready(function(){
// Allow enter key to trigger preloadorders form
    $(document).keypress(function(e) {       
      if(e.which == 13) {   
          e.preventDefault();   
                if($(".trigger").is(".ok")) 
                   $("#PreLoadOrders").trigger("click");
                else
                    return;
      }
    });
});

As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":

HTML:

<div class="modal-footer caption">
                <button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
            </div>

jQuery (include global.inc):

  $(document).ready(function(){
         // Allow enter key to trigger a particular button anywhere on page
        $(document).keypress(function(e) {
                if(e.which == 13) {
                   if($(".modal").is(":visible")){   
                        $(".modal:visible").find(".modal-close").trigger('click');
                    }
                }
         });
    });
yardpenalty.com
  • 1,244
  • 2
  • 17
  • 32