How to prevent background scrolling when Bootstrap 3 modal open on mobile platforms? On desktop browsers the background is prevented from scrolling and works as it should.<
This might be a bit like beating a dead horse here.. but, my currently implemented solution on DIY modals via vanilla JS:
On modal show:
if (document.body.style.position !== 'fixed') {
document.body.style.top = -window.scrollY + 'px';
document.body.style.position = 'fixed';
}
On modal hide:
document.body.style.position = '';
window.scrollTo(0, -parseInt(document.body.style.top, 10));
document.body.style.top = '';
I open a modal after a modal and fact the error on modal scrolling, and this css solved my problem:
.modal {
overflow-y: auto;
padding-right: 15px;
}
Try this,
body.modal-open {
overflow: hidden;
position:fixed;
width: 100%;
}
If you use jQuery you can do this with scrollTop
#modal {
bottom: 0;
position: fixed;
overflow-y: scroll;
overflow-x: hidden;
top: 0;
width: 100%;
}
$('.open-modal').click(function (e) {
e.preventDefault();
$('#modal').toggle();
scrollTo = $('body').scrollTop();
$('body').css("position", "fixed");
});
$('.close-modal').click(function (e) {
e.preventDefault();
$('#modal').toggle();
$('body').css("position", "static");
$('body').animate({scrollTop: scrollTo}, 0);
});
I know this has been answered but none of these solutions worked for me. I needed to take a different approach. I am using PhoneGap and am compiling my code natively so I had to move the background to the body. I hope this helps someone else. Or if there a cleaner way to do this please feel free to comment...
$(document).on('shown.bs.modal', '.modal', function (e) {
$("#" + e.target.id).find(".modal-backdrop").css("z-index", $("#" + e.target.id).css("z-index")).insertBefore("#" + e.target.id);
});
Courtesy of JDiApice who synthesized and extended the work of other contributors at iOS 8.x modal scroll issue #14839:
@media only screen and (max-device-width:768px) {
body.modal-open {
// block scroll for mobile;
// causes underlying page to jump to top;
// prevents scrolling on all screens
overflow: hidden;
position: fixed;
}
}
body.viewport-lg {
// block scroll for desktop;
// will not jump to top;
// will not prevent scroll on mobile
position: absolute;
}
body {
overflow-x: hidden;
overflow-y: scroll !important;
}
/* The reason the media specific is on there is
on a desktop i was having issues with when the modal would open
all content on the page would shift from centered to left.
Looked like crap. So this targets up to tablet size devices
where you would need to scroll. There is still a slight shift
on mobile and tablet but its really not much. */
Unlike the other solutions we tried, it does not scroll the background to the top after the popup modal closes.