I have written my own modal classes using css and have used it in my application successfully. However the issue i'm facing is when the overlay is open i can still scroll the background contents. How can i stop scrolling background contents when my modal/overlay is open?
This is my modal which opens on top of the overlay
<div>
  <div className="overlay"></div>
  {this.props.openModal ?
  <div>
    <div className="polaroid sixten allcmnt_bg_clr horiz_center2">
      {}
      <div className="mobile_header">
        <PostHeader/>
      </div>
      <div className="mobile_renderPost">
        { this.renderPostType() }
      </div>
      <div className="mobile_post_bottom"></div>
    </div>
  </div> : null}
</div>
my overlay css
.overlay {
  background-color: rgba(0, 0, 0, .70);
  position: fixed;
  width: 100%;
  height: 100%;
  opacity: 1;
  left: 0;
  right: 0;
  -webkit-transition: opacity .25s ease;
  z-index: 1001;
  margin: 0 auto;
}
                One approach is hidden the overflow of the body element.
like this:
body.modal-open{
    overflow:hidden;
}
so in this case when you popup the modal you add a class to body and then when you close it you remove that class.
another approach is using a javascript to disable the scroll like this:
   document.documentElement.style.overflow = 'hidden';
   document.body.scroll = "no";
and then return it with
 document.documentElement.style.overflow = 'scroll';
 document.body.scroll = "yes";
                        When you open the modal, you can add overflow: hidden; to the body's style.
Or,
body.modal-opened {
   overflow: hidden;
}
And add modal-opened class to the body when opening and remove when you close the dialog.
Using JavaScript to add a class to the body with
overflow:hidden;
will work in most cases, but I beleive Safari on iPhone will still scroll slightly with jitter due to Touch Move and something like this will be needed.
function handleTouchMove(e)
{
  e.preventDefault();
}
function lockscreen()
{
  var body = document.getElementById("body");
  body.className += " lock-screen";
  body.addEventListener('touchmove', handleTouchMove, false);
}
function unlock()
{
  var body = document.getElementById("body");
 body.classList.remove("lock-screen");
 body.removeEventListener('touchmove', handleTouchMove);
}
to stop the user from still scrolling
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With