How to hide Bootstrap modal with javascript?

JavascriptJqueryTwitter BootstrapModal Dialog

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

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

Solution 6 - Javascript

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

Solution 7 - Javascript

I found the correct solution you can use this code

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

(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

Solution 10 - Javascript

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.

Solution 11 - Javascript

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.

Solution 12 - Javascript

I used this simple code:

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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

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

Solution 19 - Javascript

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

Solution 20 - Javascript

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.

Solution 21 - Javascript

I used this code -

Hide modal with smooth effect using Fade Out.

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

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

Solution 22 - Javascript

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

Solution 23 - Javascript

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

Solution 24 - Javascript

Some times

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

does not get the job done so you need to add this to footer of your modal:

<button type="button" id="close_cred_modal" class="btn btn-secondary" data-dismiss="modal">Close</button>

and than add this line to close the modal

$('#close_cred_modal').click();

Solution 25 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjvillianView Question on Stackoverflow
Solution 1 - JavascriptLarry KView Answer on Stackoverflow
Solution 2 - JavascriptSubodh GhulaxeView Answer on Stackoverflow
Solution 3 - JavascriptRoyer VazquezView Answer on Stackoverflow
Solution 4 - JavascriptgazaView Answer on Stackoverflow
Solution 5 - JavascriptManuel FernandoView Answer on Stackoverflow
Solution 6 - JavascriptShivamView Answer on Stackoverflow
Solution 7 - JavascriptOsama khodrogView Answer on Stackoverflow
Solution 8 - JavascriptRichard HandleyView Answer on Stackoverflow
Solution 9 - JavascriptNathanView Answer on Stackoverflow
Solution 10 - JavascriptDan SchoonmakerView Answer on Stackoverflow
Solution 11 - JavascriptmarkdotnetView Answer on Stackoverflow
Solution 12 - JavascriptViktor Kisil'ovView Answer on Stackoverflow
Solution 13 - JavascriptLindsayView Answer on Stackoverflow
Solution 14 - Javascriptbrentmc79View Answer on Stackoverflow
Solution 15 - JavascriptChristophe Meheut Forik 21View Answer on Stackoverflow
Solution 16 - JavascriptLimitless isaView Answer on Stackoverflow
Solution 17 - JavascriptTylerView Answer on Stackoverflow
Solution 18 - JavascriptJaggiView Answer on Stackoverflow
Solution 19 - JavascriptPrathap KudupuView Answer on Stackoverflow
Solution 20 - JavascriptJason GodsonView Answer on Stackoverflow
Solution 21 - JavascriptSanjay SinghalView Answer on Stackoverflow
Solution 22 - JavascriptDr. XDView Answer on Stackoverflow
Solution 23 - JavascriptDaveView Answer on Stackoverflow
Solution 24 - JavascriptAmeer HamzaView Answer on Stackoverflow
Solution 25 - Javascriptuser5093161View Answer on Stackoverflow