Prevent dialog on mobile screen from scrolling the body

14,980

Solution 1

Try this:

body {
    left: 0;
    -webkit-overflow-scrolling: touch;
    position: fixed;
    top: 0;
    width: 100%;
}

Works for me (see http://jsbin.com/aXoMaGo/2) in Safari/Chrome on iOS 7 and also gives the Modal a sexy bounce-effect.


Final solution that works (even when the dialog is dismissed): https://jsbin.com/aXoMaGo/6 . The only downside to this is that it scrolls to the top of the page each time the modal is dismissed.

Solution 2

The easiest option is to use the overscroll-behavior CSS property on the popup.

.modal {
overscroll-behavior: contain;
}

This property was added to CSS specifically for this use case.

Solution 3

I had a similar issue. Typically overflow:hidden accomplishes this on desktop. For mobile you'll also need to apply position fixed. So, when your dialog is active, add a ".noscroll" class to the body:

body.noscroll{
overflow:hidden;
position:fixed;
}

Solution 4

One issue is that your event names are off for Bootstrap 3. Another is that mobile, webkit-based browsers don't seem to obey overflow: hidden on the <body>. Try this:

$(function(){
  $('#myModal').modal().on('shown.bs.modal', function(){
    $('body').css({
      position: 'fixed'
    });
  }).on('hidden.bs.modal', function(){
    $('body').css({
      position: ''
    });
  });
});

Solution 5

For all those Since I am not stisfied with the Answer it does not work on my note 8 . the screen actually freezes .

Here's the hack i created can be buggy but solves the major issue :)

js bin

Any clarifications are welcomed :)

Share:
14,980
FloatingRock
Author by

FloatingRock

Hey you!

Updated on June 04, 2022

Comments

  • FloatingRock
    FloatingRock almost 2 years

    I'm displaying a dialog on a mobile screen that's longer than the size of the screen (so it scrolls).

    Here's the problem: When you scroll past the bottom of the dialog (I happen to be using Bootstrap 3), I expect it to just stop. Instead, it starts scrolling the underlying body. I've tried everything that's been suggested in this recommended solution, and it still doesn't freaking work!

    Here's a live demo of the issue on JSbin, for your viewing pleasure

    http://jsbin.com/EdAhAsU/1/

    Note: To reproduce the issue, access it using a mobile - any mobile - and attempt to scroll past the end of the dialog. Tried it on Android, and iPhone - doesn't work for either.

    Thanks!