[javascript] How to hide Bootstrap modal with javascript?

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>

This question is related to javascript twitter-bootstrap modal-dialog

The answer is


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
    });

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();
});

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();

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>

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.


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.


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

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

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.


I used this code -

Hide modal with smooth effect using Fade Out.

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

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

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

this can be done in just HTML:

data-dismiss="modal"

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

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

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

I used this simple code:

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

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

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

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


$('#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();

(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

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

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.


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


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.


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();

$('#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

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


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.


I found the correct solution you can use this code

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation Read input from a JOptionPane.showInputDialog box Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How can I display a modal dialog in Redux that performs asynchronous actions? Angular 2.0 and Modal Dialog How to use Bootstrap modal using the anchor tag for Register? Bootstrap modal opening on page load Trying to make bootstrap modal wider How to present a modal atop the current view in Swift Send parameter to Bootstrap modal window? Set bootstrap modal body height by percentage