Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 558
CraZyDroiD Avatar asked Dec 21 '17 05:12

CraZyDroiD


3 Answers

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";
like image 138
M.R.Safari Avatar answered Oct 18 '22 02:10

M.R.Safari


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.

like image 5
adeltahir Avatar answered Oct 18 '22 02:10

adeltahir


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

like image 3
Austin Jones Avatar answered Oct 18 '22 01:10

Austin Jones