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.
On mobile browsers (Safari ios, Chrome ios, etc), when a modal is opened and using your finger to scroll it, the background also scrolls as does the modal. How do I prevent that?
No scripts needed.
BS 3 sets a .modal-open class on body that you can use to set the position and overflow values (made with LESS).
The chosen solution works, however they also snap the background to the top scrolling position. I extended the code above to fix that 'jump'.
The css is pretty simple:
Try this,
I thought you might forget to add attribute
data-toggle="modal"
to the link or button that triggers the modal popup event. Firstly, I also got the same problem but, after adding the attribute above it works well for me.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:
On modal hide:
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:
JS:
EDIT: Note, for very small modals, you might have to add the following line to your CSS: