Disable click outside of bootstrap modal area to close modal [duplicate] - javascript

This question already has answers here:
Disallow Twitter Bootstrap modal window from closing
(27 answers)
Closed 1 year ago.
I am making a bootstrap website, with a couple of Bootstrap 'Modals'.
I'm trying to customize some of the default features.
Problem is this;
You can close the modal by clicking on the background.
Is there anyway to disable this feature?
On specifc modals only?
Bootstrap modal page

On Options chapter, in the page you linked, you can see the backdrop option. Passing this option with value 'static' will prevent closing the modal.
As #PedroVagner pointed on comments, you also can pass {keyboard: false} to prevent closing the modal by pressing Esc.
If you opening the modal by js use:
$('#myModal').modal({backdrop: 'static', keyboard: false})
If you are using data attributes, use:
<button data-target="#myModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">
Launch demo modal
</button>`

This is the easiest one
You can define your modal behavior, defining data-keyboard and data-backdrop.
<div id="modal" class="modal hide fade in" data-keyboard="false" data-backdrop="static">

You can use an attribute like this: data-backdrop="static" or with javascript:
$('#myModal').modal({
backdrop: 'static',
keyboard: false // to prevent closing with Esc button (if you want this too)
})
See this answer too: Disallow twitter bootstrap modal window from closing

In my application, I am using the below piece of code to show Bootstrap modal via jQuery.
$('#myModall').modal({
backdrop: 'static',
keyboard: true,
show: true
});

You can use
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.keyboard = false;
to change the default behavior.

There are two ways to disable click outside of bootstrap model area to close modal-
using javascript
$('#myModal').modal({
backdrop: 'static',
keyboard: false
});
using data attribute in HTML tag
data-backdrop="static" data-keyboard="false" //write this attributes in that button where you click to open the modal popup.

Checkout This ::
$(document).ready(function() {
$("#popup").modal({
show: false,
backdrop: 'static'
});
$("#click-me").click(function() {
$("#popup").modal("show");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div class="modal" id="popup" style="display: none;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Standard Selectpickers</h3>
</div>
<div class="modal-body">
<select class="selectpicker" data-container="body">
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
<a id="click-me" class="btn btn-primary">Click Me</a>
</body>
<script type="text/javascript" src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/js/bootstrap.min.js"></script>
</html>

Put this code in the first block of your modal html
Bootstrap 4.x
data-keyboard="false" data-backdrop="static"
Boostrap 5.x
data-bs-keyboard="false" data-bs-backdrop="static"
Example:
<div id="modal-user" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" data-bs-keyboard="false" data-bs-backdrop="static">
Docs bootstrap 5: https://getbootstrap.com/docs/5.1/components/modal/#options
Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn't close the modal on click.

Another option if you do not know if the modal has already been opened or not yet and you need to configure the modal options:
Bootstrap 3.4
var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal
if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
$modal.modal({
keyboard: keyboard,
backdrop: backdrop
});
} else { // Modal has already been opened
$modal.data('bs.modal').options.keyboard = keyboard;
$modal.data('bs.modal').options.backdrop = backdrop;
if(keyboard === false) {
$modal.off('keydown.dismiss.bs.modal'); // Disable ESC
} else { //
$modal.data('bs.modal').escape(); // Resets ESC
}
}
Bootstrap 4.3+
var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal
if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
$modal.modal({
keyboard: keyboard,
backdrop: backdrop
});
} else { // Modal has already been opened
$modal.data('bs.modal')._config.keyboard = keyboard;
$modal.data('bs.modal')._config.backdrop = backdrop;
if(keyboard === false) {
$modal.off('keydown.dismiss.bs.modal'); // Disable ESC
} else { //
$modal.data('bs.modal').escape(); // Resets ESC
}
}
Change options to _config

Use this CSS for Modal and modal-dialog
.modal{
pointer-events: none;
}
.modal-dialog{
pointer-events: all;
}
This can resolve your problem in Modal

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">
try this,During my application development ...I also met the trouble that default values for a model attribute => data-keyboard="true",
=> data-backdrop="non static"
Hope this will help you!

The solution that work for me is the following:
$('#myModal').modal({backdrop: 'static', keyboard: false})
backdrop: disabled the click outside event
keyboard: disabled the scape keyword event

Try this:
<div
class="modal fade"
id="customer_bill_gen"
data-keyboard="false"
data-backdrop="static"
>

if you want to change default:
for bootstrap 3.x:
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.keyboard = false;
for bootstrap 4.x and 5.x:
$.fn.modal.prototype.constructor.Constructor.Default.backdrop = 'static';
$.fn.modal.prototype.constructor.Constructor.Default.keyboard = false;

Use this if you want to disable the outer click for all modals using jQuery. Add this script to your Javascript after jQuery.
jQuery(document).ready(function () {
jQuery('[data-toggle="modal"]').each(function () {
jQuery(this).attr('data-backdrop','static');
jQuery(this).attr('data-keyboard','false');
});
});

This solution worked for me:
$('#myModal').modal({backdrop: 'static', keyboard: false})
with
data-backdrop="static" data-keyboard="false"
in the button witch launch the Modal

If you are using #ng-bootstrap use the following:
Component
import { Component, OnInit } from '#angular/core';
import { NgbModal } from '#ng-bootstrap/ng-bootstrap';
#Component({
selector: 'example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.scss'],
})
export class ExampleComponent implements OnInit {
constructor(
private ngbModal: NgbModal
) {}
ngOnInit(): void {
}
openModal(exampleModal: any, $event: any) {
this.ngbModal.open(exampleModal, {
size: 'lg', // set modal size
backdrop: 'static', // disable modal from closing on click outside
keyboard: false, // disable modal closing by keyboard esc
});
}
}
Template
<div (click)="openModal(exampleModal, $event)"> </div>
<ng-template #exampleModal let-modal>
<div class="modal-header">
<h5 class="modal-title">Test modal</h5>
</div>
<div class="modal-body p-3">
<form action="">
<div class="form-row">
<div class="form-group col-md-6">
<label for="">Test field 1</label>
<input type="text" class="form-control">
</div>
<div class="form-group col-md-6">
<label for="">Test field 2</label>
<input type="text" class="form-control">
</div>
<div class="text-right pt-4">
<button type="button" class="btn btn-light" (click)="modal.dismiss('Close')">Close</button>
<button class="btn btn-primary ml-1">Save</button>
</div>
</form>
</div>
</ng-template>
This code was tested on angular 9 using:
"#ng-bootstrap/ng-bootstrap": "^6.1.0",
"bootstrap": "^4.4.1",

TLDR
backdrop: 'static'
https://getbootstrap.com/docs/3.3/javascript/#modals-options
specify static for a backdrop which doesn't close the modal on click.

none of these solutions worked for me.
I have a terms and conditions modal that i wanted to force people to review before continuing...the defaults "static" and "keyboard" as per the options made it impossible to scroll down the page as the terms and conditions are a few pages log, static was not the answer for me.
So instead i went to unbind the the click method on the modal, with the following i was able to get the desired effect.
$('.modal').off('click');

For Bootstrap 4.x, you can do like this :
$('#modal').data('bs.modal')._config.backdrop = 'static';
$('#modal').data('bs.modal')._config.keyboard = false;

You can Disallow closing of #signUp (This should be the id of the modal) modal when clicking outside of modal.
As well as on ESC button.
jQuery('#signUp').on('shown.bs.modal', function() {
jQuery(this).data('bs.modal').options.backdrop = 'static';// For outside click of modal.
jQuery(this).data('bs.modal').options.keyboard = false;// For ESC button.
})

I was missing modal-dialog that's why my close modal wasn't working properly.

You can also do this without using JQuery, like so:
<div id="myModal">
var modal = document.getElementById('myModal');
modal.backdrop = "static";
modal.keyboard = false;

Add the below css as per you want your screen width.
#media (min-width: 991px){
.modal-dialog {
margin: 0px 179px !important;
}
}

Related

Modal is transitioning error with bootstrap4 alpha6 modal

I am using bootstrap4 alpha 6 Modal, I am getting:
Error: Modal is transitioning
That happen when I am trying to re-trigger the same modal again with dynamic data through JavaScript function as following:
function openModal(title, text) {
$('.modal-title').text(title);
$('.modal-body p').text(text);
$('#modalAlert').modal('show');
}
I tried to use setTimeout function, but didn't work as in this article:
https://github.com/twbs/bootstrap/issues/21687
Any suggestions?
The quickest solution is to remove the modal 'fade' class which is throwing this error. It seems to be a known issue of the Bootsrap v6 that will be fixed in a next released.
See here
Worked with removing fade from parent div class.
Final Modal code ( Adding here for posterity ) :
HTML
<div class="modal loadingModal" id="applemodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-body">
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
<img src="ico/4.svg">
</div>
</div>
</div>
</div>
</div>
JS
$.ajax({
type: "GET",
url: "/getTimeline",
data: {
'dateTime': selected
},
async: true,
beforeSend: function () {
$('#applemodal').modal({
backdrop: 'static',
keyboard: false
});
},
success: function(data) {
$('#applemodal').modal('toggle');
}
});
i am using bootstrap 4 Modal too, My solution;
$(document).on('show.bs.modal', '.modal', function (event) {
var zIndex = 1040 + (10 * $('.modal:visible').length);
$(this).css('z-index', zIndex);
setTimeout(function() {
$('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
}, 0);
});
First open the modal and then try to find the DOM elements that's inside modal (eg. $('.modal-title') and $('.modal-body p'))
Changing the order of executing your function might work:
function openModal(title, text) {
$('#modalAlert').modal('show');
$('.modal-title').text(title);
$('.modal-body p').text(text);
}
Finally, make sure that modal is open/visible in the screen when you access HTML that's inside the modal.
Please set your button type='submit' to type='button'
My solution was to open the model programmatically rather than through the link.
Instead of:
Open My Modal
Use:
Open My Modal
$('#myLink').on('click', function(){
$('#myModal').modal('show');
})

Problems with new Google reCAPTCHA in IE when inside modal or dialog

reCAPTCHA works perfectly well in Chrome.
However, (only when reCAPTCHA iframe is inside a dialog box or a modal) in IE the placeholder won't go away.
Whatever the user writes is considered part of the placeholder (I think) and the "verify" button won't be enabled to be clicked.
The picture explains this:
The same code works perfectly well in all browsers when I take the recaptcha div outside the modal
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : '6Lc7PAATAAAAAE7JwcA7tNEDIrczjCCUvi3GiK4L'
});
};
</script>
</head>
<body>
<div class="container">
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="?" method="POST">
<div id="html_element"></div>
<br>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
The problem is generated by the the modal component of Bootstrap.
When the modal is about to appear this function is called:
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
The function adds a "focusin" event to the document to be sure that the focus is still inside the modal; if the focus goes to another element outside the modal then the latter immediately obtain it back.
Therefore, when you click inside the recaptcha form the focus' conflict causes the Internet Explorer bug.
Anyway, one possible solution is to override that method and disable the focus-back behaviour when a recaptcha component obtain the focus, but this is quite difficult to do because there is no control over the recaptcha html (how can you know if e.target is an element of recaptcha?).
My solution is to completely disable this behavior, to do this just override the enforceFocus function with an empty function:
$.fn.modal.Constructor.prototype.enforceFocus = function () { };
A more elegant solution would be apreciated. :)
Old recaptcha, i.e. version 1.0 works ok on the modal
To follow up on the response by 'Digibusiness', A little more elegant would be to override the entire bootstrap function with a practical one (on your page load - the document.ready function would be a good place).
This way, you can refer only to IE when overrding + only to iframes loaded on the modal, hence not screwing accessibility(which have become a big deal these days) all over the site just for a specific iframe-over-modal-on-a-specific-browser functionallity fix.
The code goes follows:
if (window.navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) { // If Internet Explorer
$.fn.modal.Constructor.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
if (e.target.nodeName !== "IFRAME") {
this.$element.trigger('focus')
}
}
}, this))
}
}

Focus on Input when Bootstrap Modal closes

After a blur event on an input field "bootbox1", I want to use a Bootstrap Modal for an message, after the modal closes the focus would go to the input field "bootbox2". But the input field does not get focus.
What am I doing wrong?
Demo
HTML
<input type="text" id="bootbox" />
<input type="text" id="bootbox2" />
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- dialog body -->
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal">×</button>Hello world!</div>
<!-- dialog buttons -->
<div class="modal-footer">
<button type="button" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
JS
$('#bootbox').on('blur', function checkSelection(e) {
$("#myModal").on("show", function () { // wire up the OK button to dismiss the modal when shown
$("#myModal a.btn").on("click", function (e) {
console.log("button pressed"); // just as an example...
$("#myModal").modal('hide');
$('#bootbox2').focus();
// dismiss the dialog
});
});
$("#myModal").on("hide", function () { // remove the event listeners when the dialog is dismissed
$("#myModal a.btn").off("click");
$('#bootbox2').focus();
});
$("#myModal").on("hidden", function () { // remove the actual elements from the DOM when fully hidden
$("#myModal").remove();
});
$("#myModal").modal({ // wire up the actual modal functionality and show the dialog
"backdrop": "static",
"keyboard": true,
"show": true // ensure the modal is shown immediately
});
});
//this works
$('#bootbox2').on('blur', function checkSelection(e) {
$('#bootbox').focus();
});
You need to wait for the hidden.bs.modal event to fire, not the hide.bs.modal.
According to the Bootstrap Docs for the event hide.bs.modal
This event is fired immediately when the hide instance method has been
called.
Whereas hidden.bs.modal
This event is fired when the modal has finished being hidden from the
user (will wait for CSS transitions to complete).
Since your focus is being called before the overlay has been removed the input cannot take the keyboard focus yet.

Bootstrap modal hide is not working

Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.
<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<div class="modal-bootstrap-dialog modal-sm">
<div class="modal-bootstrap-content">
<div class="modal-bootstrap-body">
-- content ----
</div>
</div>
</div>
<div class="modal-bootstrap-footer">
<button type="submit" class="button primary" data-dismiss="modal">Close</button>
<button type="submit" class="button primary">Save changes</button>
</div>
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
bootply
You are using both modal toggling methods: via Javascript and via data attributes. So your click is firing the modal show as your data attributes set, and your Javascript does not affect this trigger.
Just remove the data attributes and go with the Javascript method:
<button class="button primary" id="buy" style="text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<!-- modal contents -->
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
} else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
I had same problem. Remove fade class.
I had the same problem, tried a lot of things but the only solution that worked for me is #Tang Chanrith suggested to remove individually parts of the modal but a little bit improved to place back and the scrollbar. I'll put my answer just if the accepted answer did not work for them. Sorry for my english. Hope I helped.
#Tang Chanrith
Try this function
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Improved Sollution
You just have to delete a class from body and css that generated
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$("#myModal").hide();
}
For those still having issues (hi Googlers!), if you're using fade, you'll have to use javascript to remove fade class.
Try this function
function hideModal(){
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Remove the modal class "fade" will do.
I have solution this problem.
$('#landingpage, body').on('click',function(){
$( ".action-close" ).trigger( "click" );});
try to add return false like this:
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
return false;
});
I checked your code.
Now you compare a == 5. but a is always 4. you may have to check this why you are doing this comparison.
Also you need you remove the data-target if you want to open modal from javascript :
<button class="button primary" id="buy" data-toggle="modal" style="text-decoration:none;" type="button">Review and confirm</button>
data-target directly opening the modal.
Check if this is working.
You should try this $('.modal.in').modal('hide')
Via https://github.com/twbs/bootstrap/issues/489
I had the same problem, my mistake was that I was trying to open the modal window a few times. We must test that the modal window is not already open before trying to open it.
if (!($("#MyModal").data('bs.modal') || {})._isShown){
$("#MyModal").modal('show');
}
Hide modal dialog box using bootstrap
Method 1: using bootstrap
$('.close').click();
$("#MyModal .close").click();
$('#myModalAlert').modal('hide');
Method 2: using stop-propagation
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Method 3: After shown method invoke
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
Method 4: Using CSS
this.display='block'; //Set block css
this.display='none'; //set none css after close dialog
In the java script code you need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
As I encountered, sometimes you need to remove display style:
style="display: block;"
I had the same issue. I tried the JavaScript way suggested in the post, unfortunately it only worked half of the time. If I triggered my modal a few times, it bugs out. As a result I created a work around using CSS:
/* Hide the back drop*/
.modal-backdrop.show {
display: none;
}
/* Simulate the backdrop using background color */
.modal-open .modal {
background-color: rgba(47, 117, 19, 0.3);
}
I was opening the modal popup when I click on the link using data-toggle="modal" attribute which was bound with that link and trying to close it using javascript but I was failed each time, so when I remove the "data-toggle" attribute and "href" from that link and opened it using javascript then it was closing properly using javascript as well.
from the below few lines of code, you can understand easily
Advanced Search
I changed the above link to something link this
Advanced Search
After that when I try to close it using javascript, then I become successful
$("#CustomerAdvancedModal").modal('hide');
I am also having the same problem, where I can't find the correct solution for it.
Later I observed that what is happening when the modal gets closed when it works well.
Three Main properties are,
modal-open class gets removed from <body> tag.
In <body> tag change CSS .
<div> class of modal-backdrop gets removed.
So, When u do these things manually, you will achieve it, when not works.
The code should be as following in Jquery,
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$(".modal-backdrop").remove();
$('#myModal').hide();
Hence, try this and get a solution.
Before you open a loading modal, make sure that you close all others.
This is the function is use to close the modal:
function hideLoadingModal() {
$('#loadingModal').on('shown.bs.modal', function () {
$('#loadingModal').modal('hide');
});
}
Now if I want to open the modal I call the above function and open a new one after that.
Like this:
hideLoadingModal();
$('#loadingModal').modal('show');
Hope this helps you.
Cheers
One possible reson should be the order of jquery and bootstrap and your script is not in proper sequence.
Below should be the sequence.
1. <script src='js/jquery-3.2.1.min.js'></script>
2. <script src='js/bootstrap.min.js'></script>
3. your own script:
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
Check if you closed all nested div inside main modal div
<div data-backdrop="static" class="modal fade" id="modal-progress" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
-----NESTED DIV ------------------
</div>
None of the above solutions worked for me. If this is your case, try to imitate click event on the close button (the one which is added dynamically):
<div class="modal" tabindex="-1" role="dialog" id="modal" area-hidden="true" style="display: inline-block;">
<div class="modal-dialog modal-dialog-centered" role="document">
...
</div>
Close</div>
</div>
$('.close-modal').click() should resolve the issue.
Try this
give an id to close button
<button type="submit" id="modalcloseBtn" class="button primary" data-dismiss="modal" >Close</button>
and trigger onclick event
$('#modalcloseBtn').trigger("click");
G.modals = [];
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const openModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const modalNode = document.querySelector(`#${modalId}`);
modal = new bootstrap.Modal(modalNode);
modal.show();
const modalObject = {
modal,
id: modalId
};
G.modals.push(modalObject);
callback();
};
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const closeModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const currentModal = G.modals.find(item => item.id === modalId) || false;
if(!currentModal) return;
const { modal } = currentModal;
const { _element, _backdrop } = modal;
_element.classList.remove('show');
_backdrop._element.remove();
G.modals.splice(G.modals.indexOf(currentModal), 1);
callback();
};
openModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalOpened();
}
});
closeModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalClosed();
}
});
if nothing helps (that happens) - make sure that nobody prevents it like below (my case):
$modal.on('hide.bs.modal', function (e) {
if (shouldNotBeClosed) {
return e.preventDefault();
}
});
Same issue here for no reason, i'm not using "fade" stuff.
I open modal and close modal only with js, the hide function is working only when called inside a setTimeout.
<script>
var modal_show = function(){
$("#modal_post").modal("show");
};
var modal_hide = function(){
$("#modal_post").modal("hide");
};
window.addEventListener("message", function(event){
// listening iframe post message
modal_hide();
});
</script>
<div class="modal" id="modal_post" tabindex="-1" role="dialog" style="width: 100%;" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog" style="width: 450px; height:600px; background: white; border: none; box-shadow: none;" role="document">
<div class="modal-content" style="width: 100%; background: white; border: none; box-shadow: none;">
<div class="modal-body" style="width: 100%; background: white; border: none; box-shadow: none; padding: 0;">
<div>
<iframe src="https://perdu.com" style="width:450px;height:600px;"></iframe>
</div>
</div>
</div>
</div>
</div>
For no reason, modal_hide(); is working inside the console but not in my code.
If i replace the modal_hide(); in the event listener with setTimeout(modal_hide, 200); it's working properly
its very easy.. Remove fade class :)

JQuery scroll to top of Bootstrap Modal

I'm currently using the bootstrap modal plugin to display long legal messages on a website I'm designing, but the problem is that if you open one modal after the other, the second one will already be scrolled to whatever position the first one was. So I'm looking for a way to scroll a div to the top with JS/JQuery. This is the code I'm using currently:
HTML:
<!--MODAL-->
<div id="modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="modalTitle" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="modalTitle"></h3>
</div>
<div id="modal-content" class="modal-body">
</div>
<div class="modal-footer">
<button id="modalPrint" class="btn btn-info hidden-phone" onClick=''>Print</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
Javascript:
function openModal(heading, url) {
$.ajax({
url: url,
cache: false
}).done(function( html ) {
$("#modal-content").html(html);
$("#modalTitle").html(heading);
$('#modalPrint').attr('onClick', 'loadPrintDocument(printCookies, {attr : "href", url : '+ url +', showMessage: false, message: "Please wait while we create your document"})');
$('#modal').modal('show');
$("#modal-content").scrollTop(0);
});
}
As you can see, I've tried scrolling to the top after the modal has been shown. Any ideas?
Now with bootstrap 3 the events has change an can be achieved like this (plus a smooth animation to the top)
$('#modal').on('shown.bs.modal', function () {
$('#modal').animate({ scrollTop: 0 }, 'slow');
});
Okay I've answered my own question. For anyone else with this issue, simply add this function to your JS!
$('#modal').on('shown', function () {
$("#modal-content").scrollTop(0);
});
I will leave this question up, as there isn't one similar (that I could find) and it may help someone
On Bootstrap 4 (v4.0.0-alpha.6) the following worked well for me:
$('#Modal').show().scrollTop(0);
Please note as of bootstrap-4.0.0-beta.1 and Firefox 56.0.1 this does not seem to work correctly;
I checked IE11, MS Edge and Chrome and this works fine.
In Bootstrap 4, the following works for me:
$('.modal-body').scrollTop(0);
You need to scrollTop on the modal-body because the parent elements (modal, modal-dialog, modal-content) are containers and do not scroll with the user.
However, if you prefer a less jerky movement, try the animation route:
$('.modal-body').animate({scrollTop: 0},400);
Scroll up button has a class of: .page-scroll
Modal with a class of: .modal
JS to make scroll happen with the modal (JS could be simplified):
$('body').on('click', '.page-scroll', function(event) {
var $anchor = $(this);
$('html, body, .modal').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
There was change in boostrap where you need to use: on shown.bs.modal
Call a function when you show the modal window (I opted for this method)
<button onclick="showSMSSummary(); return false;"
data-toggle="tooltip" title="Click To View Summary"
class="btn btn-primary btn-sm">SMS Summary</button>
function showSMSSummary()
{
$('#HelpScreenModalContent').modal('show');
$('#HelpScreenModal').animate({ scrollTop: 0 }, 'fast');
}
ScrollTop bootbox modal on fadeIn The answer is in this issue.
When setting up bootbox dialog add .off("shown.bs.modal");this at the end.
bootbox.dialog({ ... }).off("shown.bs.modal");
It will scroll be at top when open dialog.

Categories

Resources