311
votes

I've read the posts here, the Bootstrap site, and Googled like mad - but can't find what I'm sure is an easy answer...

I have a Bootstrap modal that I open from a link_to helper like this:

<%= link_to "New Contact", new_contact_path, {remote: true, 'data-toggle' => 'modal', 'data-target' => "#myModal",  class: "btn btn-primary"} %>

In my ContactsController.create action, I have code that creates Contact then passes off to create.js.erb. In create.js.erb, I have some error handling code (a mix of ruby and javascript). If everything goes well, I want to close the modal.

This is where I'm having trouble. I can't seem to dismiss the modal when all goes well.

I've tried $('#myModal').modal('hide'); and this has no effect. I've also tried $('#myModal').hide(); which causes the modal to dismiss but leaves the backdrop.

Any guidance on how to close the modal and/or dismiss the backdrop from within create.js.erb?

Edit

Here's the markup for myModal:

<div class="modal hide" id="myModal" >
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Add Contact</h3>
    <div id="errors_notification">
    </div>
  </div>
  <div class="modal-body">
    <%= form_for :contact, url: contacts_path, remote: true do |f| %>  
      <%= f.text_field :first_name, placeholder: "first name" %>
      <%= f.text_field :last_name, placeholder: "last name" %>
      <br>
      <%= f.submit "Save", name: 'save', class: "btn btn-primary" %>
      <a class="close btn" data-dismiss="modal">Cancel</a>
    <% end %>
  </div>
  <div class="modal-footer">
  </div>
</div>
25
$('#myModal').modal('hide'); is the correct syntax to close/hide the modal with id myModal (you can test this on the Bootstrap documentation page). Are you sure you have an element with this id on your page? Also, what are you trying to accomplish with this call? Your current implementation performs an Ajax request to new_contact_path and at the same time opens the modal with the contents of #myModal – is this what you want?Julian D.
Hi, Julian. I posted myModal markup above and there is, indeed, a div with id myModal. I re-tried $('myModal').modal('hide') and still no good. HM. In terms of what I'm trying to accomplish, I think it may have been incorrect to use the link_to helper. I've replaced this with: <a data-toggle="modal" href="#myModal" class="btn btn-primary">Add Contact</a> since I don't really need a call to new_contact_path. I just want the modal to open and then deal with user input. Thanks for taking the time to respond. I'll see if I can't sort this out.jvillian
I guess it's just a typo, but the call should be $('#myModal').modal('hide');(there is an # missing in your comment).Julian D.
My bad for typing instead of copying from actual code. The actual code reads: $('#myModal').modal('hide'). Jjvillian
You can try using bootboxjsmd. ariful ahsan

25 Answers

530
votes

With the modal open in the browser window, use the browser's console to try

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

If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.

If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?

Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.

82
votes

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 non of the above method work, give a id to your close button and trigger click on close button.

61
votes

The Best form to hide and show a modal with bootstrap it's

// SHOW
$('#ModalForm').modal('show');
// HIDE
$('#ModalForm').modal('hide');
54
votes

I use Bootstrap 3.4 For me this does not work

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

In desperation,I did this:

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

Maybe it's not elegant, but it works

46
votes

I was experiencing with that same error and this line of code really helps me.

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

$('body').removeClass('modal-open'); 
//modal-open class is added on body so it has to be removed

$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class
22
votes

I found the correct solution you can use this code

$('.close').click(); 
12
votes

(Referring to Bootstrap 3), To hide the modal use: $('#modal').modal('hide'). But the reason the backdrop hung around (for me) was because I was destroying the DOM for the modal before 'hide' finished.

To resolve this, I chained the hidden event with the DOM removal. In my case: this.render()

var $modal = $('#modal');

//when hidden
$modal.on('hidden.bs.modal', function(e) { 
  return this.render(); //DOM destroyer
});

$modal.modal('hide'); //start hiding
11
votes

I ran into what I believe was a similar issue. The $('#myModal').modal('hide'); is likely running through that function and hits the line

if (!this.isShown || e.isDefaultPrevented()) return

The issue is that the value isShown may be undefined even if the modal is displayed and the value should be true. I've modified the bootstrap code slightly to the following

if (!(typeof this.isShown == 'undefined') && (!this.isShown || e.isDefaultPrevented())) return

This seemed to resolve the issue for the most part. If the backdrop still remains you could always add a call to manually remove it after the hide call $('.modal-backdrop').remove();. Not ideal at all but does work.

10
votes

I had better luck making the call after the "shown" callback occurred:

$('#myModal').on('shown', function () {
      $('#myModal').modal('hide');
})

This ensured the modal was done loading before the hide() call was made.

9
votes

What we found was that there was just a slight delay between the call to our server code and the return to the success call back. If we wrapped the call to the server in the $("#myModal").on('hidden.bs.modal', function (e) handler and then called the $("#myModal").modal("hide"); method, the browser would hide the modal and then invoke the server side code.

Again, not elegant but functional.

 function myFunc(){
        $("#myModal").on('hidden.bs.modal', function (e) {
            // Invoke your server side code here.
        });
        $("#myModal").modal("hide");
 };

As you can see, when myFunc is invoked, it will hide the modal and then invoke the server side code.

8
votes

I used this simple code:

$("#MyModal .close").click();
6
votes

I was experiencing the same problem, and after a bit of experimentation I found a solution. In my click handler, I needed to stop the event from bubbling up, like so:

$("a.close").on("click", function(e){
  $("#modal").modal("hide");
  e.stopPropagation();
});
6
votes

Here is the doc: http://getbootstrap.com/javascript/#modals-methods

Here is the method: $('#myModal').modal('hide')

If you need to open several times the modal with different content, I suggest to add (in you main js):

$('body').on('hidden.bs.modal', '.modal', function () {
      $(this).removeData('bs.modal');
    });

So you will clean the content for the next opening and avoid a kind of caching

6
votes
$('.modal-backdrop').hide(); // for black background
$('body').removeClass('modal-open'); // For scroll run
$('#modal').modal('hide'); 
6
votes

$('#modal').modal('hide'); and its variants did not work for me unless I had data-dismiss="modal" as an attribute on the Cancel button. Like you, my needs were to possibly close / possibly-not close based on some additional logic so clicking a link with data-dismiss="modal" outright would not do. I ended up having a hidden button with data-dismiss="modal" that I could programmatically invoke the click handler from, so

<a id="hidden-cancel" class="hide" data-dismiss="modal"></a>
<a class="close btn">Cancel</a>

and then inside the click handlers for cancel when you need to close the modal you can have

$('#hidden-cancel').click();
5
votes

Even I have the same kind of issues. This helped me a lot

$("[data-dismiss=modal]").trigger({ type: "click" });
5
votes

Hiding modal backdrop works but then any subsequent opening of the modal and the backdrop doesn't hide like it should. I found this works consistently:

// SHOW
$('#myModal').modal('show')
$('.modal-backdrop').show();

// HIDE
$('#myModal').modal('hide');
$('.modal-backdrop').hide();
3
votes

We need to take care of event bubbling. Need to add one line of code

$("#savechanges").on("click", function (e) {
        $("#userModal").modal("hide");
        e.stopPropagation(); //This line would take care of it
    });
3
votes

I realize this is an old question, but I found that none of these were really what I was looking for exactly. It seems to be caused by trying to close the modal before it's finished showing.

My solution was based on @schoonie23's answer but I had to change a few things.

First, I declared a global variable at the top of my script:

<script>
    var closeModal = false;
    ...Other Code...

Then in my modal code:

$('#myModal').on('show.bs.modal', function (event) {
    ...Some Code...
    if (someReasonToHideModal) {
        closeModal = true;
        return;
    }
    ...Other Code...

Then this: (Note the name 'shown.bs.modal' indicating that the modal has shown completely as opposed to 'show' that triggers when the show event is called. (I originally tried just 'shown' but it did not work.)

$('#myModal').on('shown.bs.modal', function (event) {
    if (closeEditModal) {
        $('#myModal').modal('hide');
        closeModal = false;
    }
});

Hope this saves someone the extra research some day. I spent a bit looking for a solution before I came up with this.

2
votes

I used this code -

Hide modal with smooth effect using Fade Out.

$('#myModal').fadeOut();

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

$('.modal-open').css({'overflow': 'visible'});
1
votes

If you're using the close class in your modals, the following will work. Depending on your use case, I generally recommend filtering to only the visible modal if there are more than one modals with the close class.

$('.close:visible').click();
1
votes

document.getElementById('closeButton').click(); // add a data-dismiss="modal" attribute to an element in the modal and give it this id

-1
votes

This is the bad practice but you can use this technique to close modal by calling close button in javascript. This will close modal after 3 seconds.

<!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/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
window.onload=function()
{
setInterval(function(){ 

$("#closemodal").click();
}, 3000);

}
</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" id="closemodal">Close</button>
    </div>
  </div>

</div>
</div>

 </div>

</body>
</html>
-5
votes

this can be done in just HTML:

data-dismiss="modal"

<button type="button" class="btn btn-secondary" data-dismiss="modal">Save</button>