I am showing a Bootstrap modal window for loading when performing AJAX calls. I broadcast a \"progress.init\" event when the loading modal should show and a \"progress.finis
try this
$('.modal').on('hide.bs.modal', function () {
if ($(this).is(':visible')) {
console.log("show modal")
$('.modal-backdrop').show();
}else{
console.log("hidden modal");
$('.modal-backdrop').remove();
}
})
After inspecting the element, the div
with the modal-backdrop
class still remains after I hit the browser back button, so I simply remove it:
$(window).on('popstate', function() {
$(".modal-backdrop").remove();
});
This is for someone who cannot get it fixed after trying almost everything listed above. Please go and do some basic checking like the order of scripts, referencing them and stuff. Personally, I used a bundle from bootstrap that did not let it work for some reason. Switching to separate scripts made my life a lot easier. So yeah! Just-in-case.
The best and simple approach is by using the data-dismiss
attribute. Basically the data-dismiss
attribute will dismiss the modal and you won't see the backdrop remaining.
All you need to do is adding the following at the place where you want to close your modal:
data-dismiss="modal"
For example, I have a button and when someone clicks the button it will close the modal.
<button class="btn btn-info float-right" onclick="foo()" data-dismiss="modal">Save changes</button>
You can also handle the JavaScript function on onClick
and it will close the modal and also run the JavaScript function.
This is the best approach to do using the data-dismiss
attribute.
Another possible case (mine) - you are adding modal html dynamically to DOM and it contains more the 1 root node. Gotcha here is that comment nodes also count, so, if you copied template from bootstrap site - you have them.
Using the code below continuously adds 7px padding on the body element every time you open and close a modal.
$('modalId').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();`
For those who still use Bootstrap 3, here is a hack'ish workaround.
$('#modalid').modal('hide');
$('.modal-backdrop').hide();
document.body.style.paddingRight = '0'
document.getElementsByTagName("body")[0].style.overflowY = "auto";