jvillian
jvillian

Reputation: 20253

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>

Upvotes: 361

Views: 896609

Answers (28)

Harat
Harat

Reputation: 1366

Without JQuery

HTML Changes: Just Add Class "closeModalBtn" to

<button data-bs-dismiss="modal">Close</button>

to

<button class="closeModalBtn" data-bs-dismiss="modal">Close</button>

Add Javascript:

Array.from(document.getElementsByClassName('closeModalBtn')).forEach(function(element){element.click();})

The Above example close all the opened Modal.

Upvotes: 2

Post Impatica
Post Impatica

Reputation: 16453

In my case I was apparently trying to close the dialog too fast after showing it. So in my close modal function I used this:

setTimeout(() => {
    $('#loadingModal').modal('hide');
}, 300);

Upvotes: 6

George
George

Reputation: 2960

I was facing a similar problem where my custom modal would show via js but I could not hide it (there was no close button).

For me the solution was to add the content into a modal-dialog.

<div class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="loading">
  <div class="modal-dialog">
    loading
  </div>
</div>

Without the modal-dialog it would happily show the modal, but it was impossible to hide it without the manual solutions in some of the answers here, some of which prevent you then being able to show the modal again.

Upvotes: 1

Ameer Hamza
Ameer Hamza

Reputation: 67

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

Upvotes: -1

Lindsay
Lindsay

Reputation: 101

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

Upvotes: 10

Dr. XD
Dr. XD

Reputation: 49

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

Upvotes: 2

Viktor Kisil&#39;ov
Viktor Kisil&#39;ov

Reputation: 91

I used this simple code:

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

Upvotes: 9

Dave
Dave

Reputation: 19

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

Upvotes: 0

Sanjay Singhal
Sanjay Singhal

Reputation: 19

I used this code -

Hide modal with smooth effect using Fade Out.

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

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

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

Upvotes: 1

Royer Vazquez
Royer Vazquez

Reputation: 721

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

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

Upvotes: 71

Tyler
Tyler

Reputation: 81

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

Upvotes: 6

Shivam
Shivam

Reputation: 411

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

Upvotes: 30

markdotnet
markdotnet

Reputation: 2556

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.

Upvotes: 10

Osama khodroj
Osama khodroj

Reputation: 1230

I found the correct solution you can use this code

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

Upvotes: 30

Jaggi
Jaggi

Reputation: 170

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

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

Upvotes: 6

user5093161
user5093161

Reputation:

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>

Upvotes: -1

Limitless isa
Limitless isa

Reputation: 3802

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

Upvotes: 6

Jason Godson
Jason Godson

Reputation: 316

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.

Upvotes: 3

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

Upvotes: 6

Prathap Kudupu
Prathap Kudupu

Reputation: 1353

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

Upvotes: 3

gaza
gaza

Reputation: 619

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

Upvotes: 60

Manuel Fernando
Manuel Fernando

Reputation: 491

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

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

Upvotes: 49

Dan Schoonmaker
Dan Schoonmaker

Reputation: 139

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.

Upvotes: 10

Subodh Ghulaxe
Subodh Ghulaxe

Reputation: 18671

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.

Upvotes: 88

Nathan
Nathan

Reputation: 569

(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

Upvotes: 11

brentmc79
brentmc79

Reputation: 2541

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

Upvotes: 6

Richard Handley
Richard Handley

Reputation: 111

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.

Upvotes: 11

Larry K
Larry K

Reputation: 49114

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.

Upvotes: 596

Related Questions