Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BootStrap Modal background scroll on iOS

So there is this known issue with modal on iOS, when the modal is enabled swiping up/down will scroll the body instead of the modal.

Using bootstrap 3.3.7

Tried to google it, most suggested adding

body.modal-open {
  overflow: hidden !important;
}

but it doesn't work.

Some suggested,

body.modal-open {
  position: fixed;
}

But background will jump to the top of the page.

So for now I am using,

body.modal-open {
  overflow: hidden !important;
  position: fixed;
  width: 100%;
}
#exampleModal {
  background: black;
}

As a work-around so the jump can't be seen(but still noticeable)

Is there other solutions to this?

This is the site i am working on http://www.einproductions.com/

like image 717
juniortan Avatar asked Apr 22 '17 19:04

juniortan


People also ask

Can you scroll within a modal?

Bootstrap 4.3 added new built-in scroll feature to modals. This makes only the modal-body content scroll if the size of the content would otherwise make the page scroll. To use it, just add the class modal-dialog-scrollable to the same div that has the modal-dialog class.

How do I enable scrolling in modal?

Use the . modal-dialog-scrollable class to enable scrolling inside the modal.

How Do I Stop background scroll when modal is open?

Approach: A simple solution to this problem is to set the value of the “overflow” property of the body element to “hidden” whenever the modal is opened, which disables the scroll on the selected element.


1 Answers

I've taken the solutions of @Aditya Prasanthi and @JIm, since one fixes the background-scrolling and the other fixes the skip-to-the-top after closing the modal, and turned them into one bare-minimum JS script:

let previousScrollY = 0;

$(document).on('show.bs.modal', () => {
    previousScrollY = window.scrollY;
    $('html').addClass('modal-open').css({
        marginTop: -previousScrollY,
        overflow: 'hidden',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        position: 'fixed',
    });
}).on('hidden.bs.modal', () => {
    $('html').removeClass('modal-open').css({
        marginTop: 0,
        overflow: 'visible',
        left: 'auto',
        right: 'auto',
        top: 'auto',
        bottom: 'auto',
        position: 'static',
    });
    window.scrollTo(0, previousScrollY);
});

It's, of course, possible and even adviced to use a class to set and unset the CSS for the body, however, I choose this solution to resolve a problem just in one place (and not require external CSS as well).

like image 104
Klaas van der Weij Avatar answered Sep 18 '22 18:09

Klaas van der Weij