Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close bootstrap modal without using "hide" and "data-dismiss"

I want to close bootstrap modal box conditionally. If I use $('#modal').modal('hide'); this, some thing goes wrong with my code. And If I use data-dismiss="modal" in the HTML template, modal dismiss action performs before my actual functionality should be perform on button click.

So, there is any other way to close bootstrap modal or any idea to use data-dismiss="modal" at run time?

like image 332
Ruchi Agarwal Avatar asked Jun 06 '13 21:06

Ruchi Agarwal


People also ask

How do I close a Bootstrap modal?

Clicking on the modal “backdrop” will automatically close the modal. Bootstrap only supports one modal window at a time.

How do you close a modal in a modal?

Answer: Use the modal('hide') Method You can simply use the modal('hide') method to hide or close the modal window in Bootstrap using jQuery.

How do you close a modal by clicking outside?

Another way to dismiss the modal when clicking outside involved taking advantage of the bubbling nature of the javascript events. clicking on . modal will cause the click event to propagate like this . modal -> #modal-root -> body while clicking outside the modal will only go through #modal-root -> body .

How do you prevent Bootstrap modal from hiding when clicked outside the content area?

When the Button is clicked, the HTML DIV is referenced using jQuery and its modal function is called along with properties data-backdrop: "static" and data-keyboard: false which disables the closing of the Bootstrap Modal Popup when clicked outside.


1 Answers

You can do it with auto modal closing behavior which uses the data-dismiss attribute itself or with the manual modal opening (as i guess you are doing currently) , by subscribing to hide event and use preventDefault on the event.

$('yourmodalselector').on('hide',function(e){
   if(yourConditionNotToCloseMet){
      e.preventDefault();
   }
});

Demo

Demo2

See Documentation

hide event event is fired immediately when the hide instance method has been called, which gets called wither way and this is the best place to prevent the modal from closing.

like image 88
PSL Avatar answered Oct 16 '22 03:10

PSL