Search code examples
javascripthtmlcssscrolloverlay

Prevent background scrolling when overlay appears


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;
}

Solution

  • 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";