How to hide Bootstrap modal with javascript?
Asked Answered
A

28

358

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>
Allo answered 5/5, 2012 at 21:26 Comment(6)
$('#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?Oestriol
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.Allo
I guess it's just a typo, but the call should be $('#myModal').modal('hide');(there is an # missing in your comment).Oestriol
My bad for typing instead of copying from actual code. The actual code reads: $('#myModal').modal('hide'). JAllo
You can try using bootboxjsWorried
Minor comment here, but in your markup, your #myModal element already has the class '.hide' in it? Applying that class to that element by hand would cause the modal closing behavior to be erratic (e.g. the modal box would hide, but not the gray overlay behind it). Just a thought.Proportional
G
591

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.

Gownsman answered 7/5, 2012 at 11:55 Comment(3)
The second paragraph was what I was looking for. Duplicate ID's were making my modals not to show correctly the second time.Girondist
Please mentioned the bootstrap version here. it will dot work on current bootstrapAby
Different versions of Bootstrap e.g. 4.6.1 and 5.0.1 was loaded on same page in my case, that is why modal hiding did not worked!Ferrell
E
88

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.

Equuleus answered 30/6, 2014 at 6:9 Comment(1)
This is especially useful when you know exactly at what point the modal dialog is supposed to close. For example at the end of a success function. That way if there is an error, the dialog can display it.Commemorative
D
68

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

// SHOW
$('#ModalForm').modal('show');
// HIDE
$('#ModalForm').modal('hide');
Didst answered 9/9, 2016 at 4:8 Comment(1)
Best answer by far. Simulating behavior with clicks, jQuery fadeOut or css can create misalignments in the long run.Gaudery
S
59

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

Solnit answered 10/4, 2015 at 11:30 Comment(6)
It would be better if you use $(".modal-backdrop").remove();Wingback
this will introduce new bugs. please use recommend methods,Semang
jQuery('.modal-backdrop').click();Schwitzer
little buggy but surely works. Manuel Fernando's solution below worked perfectly for me.Eyewitness
@Umingo please recommend a method if the ones mentioned here are no good and you know of one.Nidify
Thanks @Gaza, in times of desperation we need heroes like you.Philpott
D
49

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

$("[data-dismiss=modal]").trigger({ type: "click" });
Decolorant answered 30/11, 2014 at 21:13 Comment(2)
I've read another issue that suggested the problem could be having the data-dismiss attribute on the element, then on top of this attempting to trigger it from javascriptPreposition
Many Many Many thanks Manuel, this after a lot of search solved my problem, $('#MyModelId').modal('hide'); $("[data-dismiss=modal]").trigger({ type: "click" }); that i wanted to close the modal on ajax success .... really many thanks my dearLaevo
A
30

I found the correct solution you can use this code

$('.close').click(); 
Antepenult answered 2/1, 2016 at 12:34 Comment(2)
best solution so farWycliffite
superb simply is the best +1Incunabulum
E
30
$('#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
Erosion answered 2/1, 2017 at 9:35 Comment(1)
it worked, but broke down modal if I open it again modal doesn't scroll anymoreWycliffite
F
11

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.

Fistulous answered 1/11, 2012 at 23:18 Comment(0)
R
11

(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
Religious answered 29/4, 2014 at 20:8 Comment(1)
but can you please tell me about this.render() its showing undefined is not a function in my chrome console.Vernalize
N
10

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.

Nosebleed answered 17/7, 2014 at 16:31 Comment(0)
P
10

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.

Pucka answered 16/9, 2016 at 18:28 Comment(0)
M
10

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();
Mythopoeic answered 19/11, 2020 at 15:49 Comment(0)
M
8

I used this simple code:

$("#MyModal .close").click();
Microvolt answered 11/5, 2019 at 12:6 Comment(0)
R
6

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();
});
Ruination answered 11/7, 2013 at 19:51 Comment(0)
H
6

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

Hypothetical answered 6/11, 2015 at 17:7 Comment(0)
E
6
$('.modal-backdrop').hide(); // for black background
$('body').removeClass('modal-open'); // For scroll run
$('#modal').modal('hide'); 
Evieevil answered 6/6, 2016 at 12:36 Comment(0)
I
6

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

$("[data-dismiss=modal]").trigger({ type: "click" });
Ironbound answered 10/10, 2016 at 14:30 Comment(0)
P
6

$('#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();
Photogrammetry answered 27/2, 2017 at 17:34 Comment(1)
In my case (asp net razor page) I had it similiar to the OP: i had an somewhat empty div with class "modal" and dynamically added a cshtml file to it, e.g. the modal body and added a click to a button of this body as soon as the modal would be shown. calling ".modal('hide)" alone was not sufficient, as you pointed out: "data-dismiss="modal"" on the invoking button was the deal!!! tyLatimer
S
5

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);
Solicitous answered 12/7, 2022 at 12:33 Comment(0)
F
3

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
    });
Fenderson answered 20/8, 2015 at 12:31 Comment(0)
A
3

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.

Aquiline answered 19/3, 2016 at 0:40 Comment(0)
A
2

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

Abeyance answered 4/5, 2020 at 20:49 Comment(0)
S
2

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.

Semiweekly answered 5/4 at 6:49 Comment(0)
M
1

I used this code -

Hide modal with smooth effect using Fade Out.

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

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

$('.modal-open').css({'overflow': 'visible'});
Merras answered 9/5, 2019 at 19:28 Comment(0)
S
1

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.

Scummy answered 17/6, 2022 at 13:55 Comment(0)
S
0

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();
Suint answered 7/4, 2019 at 16:57 Comment(0)
D
-1

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>
Dyspepsia answered 7/10, 2016 at 7:26 Comment(0)
P
-1

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();
Phonoscope answered 18/1, 2022 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.