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.<
Using position:fixed has the side effect of scrolling the body to the top.
If you do not your body to scroll to the top, DO NOTE use position:fixed. Just disable touchmove on the body if the modal is open.
Note: The modal itself is still able to scroll on touch (if larger than the screen).
CSS:
body.modal-open {
overflow: hidden;
width: 100%;
/* NO position:fixed here*/
}
JS:
$('.modal').on('show.bs.modal', function (ev) { // prevent body from scrolling when modal opens
$('body').bind('touchmove', function(e){
if (!$(e.target).parents().hasClass( '.modal' )){ //only prevent touch move if it is not the modal
e.preventDefault()
}
})
})
$('.modal').on('hide.bs.modal', function (e) { //unbind the touchmove restrictions from body when modal closes
$('body').unbind('touchmove');
})
EDIT: Note, for very small modals, you might have to add the following line to your CSS:
.modal-dialog{
height: 100%;
}