Prevent body from scrolling when a modal is opened.


Here, in this article we will learn on how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript.

The scroll event is not cancelable. So, we cannot just disable scroll in our website using CSS or using a eventListener. However we can use the mousewheel and wheel event, to stop the scroll in our webpage when the modal us opened.

What is a wheel event in JavaScript?

A wheel event is triggered whenever the user rotates the wheel button or a pointing device (usually mouse) to navigate through the web-page.

NOTE : A wheel event is different from a scroll event. The action of a wheel event is implementation specific and it does not dispatch a scroll event.

scroll event fires when the user scrolls any element using mouse or arrow keys or scrollbar.

wheel event fires only when mouse-wheel is use.

In this article we will see an example where the default scroll of the body is disable when a modal or a pop-up is opened.

Prevent Scrolling when modal is opened

First we will code our html page, here I have div with id modal-wrapper and inside it we have another div with id modal-body . This is the main body of the modal. And I have a button call Open Modal with a onclick event.

HTML code :

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="./style.css">
  </head>
  <body>
      <div id="content">
        <button onclick="openModal()">Open Modal</button>
     
        <div id="modal-wrapper">
          <div id="modal-body">
            <p>This is a modal</p>
              <button onclick="closeModal()">Close Modal</button>
          </div>
        </div>

        Lorem ipsum, dolor sit amet consectetur adipisicing elit. Explicabo sequi accusamus voluptas adipisci nam rem aspernatur totam quis enim facere sunt autem eveniet molestiae dolores, ut soluta dolor porro nesciunt dignissimos praesentium voluptates corporis? Eveniet autem dolore rerum nobis minus fuga debitis accusantium. Repellendus ratione distinctio vitae dolorum, corrupti, ad dignissimos quia recusandae accusamus quidem in tempora vel, iure voluptas? Adipisci id veritatis dicta, non mollitia dolor. Dignissimos nesciunt recusandae maxime earum eos odit quas saepe excepturi consequuntur quisquam esse blanditiis ducimus error, distinctio cupiditate? Architecto voluptates nisi aperiam perspiciatis a assumenda tenetur dolore vero quisquam consequuntur possimus ducimus qui corrupti officia culpa nihil iure, eveniet sed, sequi cum atque magnam quas nam. Quidem odio dolore sed magnam architecto repudiandae vel, enim ducimus eaque nihil dolorum esse ullam veniam ad eveniet! Quos sequi placeat quo doloremque amet vero omnis suscipit harum minima dicta dolores provident reprehenderit doloribus, cumque quaerat nulla porro. Eligendi rem, dolores dolorem itaque dignissimos unde nobis quis incidunt aut commodi quidem necessitatibus iusto asperiores assumenda, nihil placeat molestias perspiciatis labore soluta officia vero velit aliquam at. Placeat voluptas perferendis laborum incidunt ipsa. Accusantium odit a eaque minima dignissimos dolores repellendus blanditiis esse, quasi dicta. Quis, in aliquam.
    </div>

    <script src="main.js"></script>
  </body>
</html>

style.css :

body,
html{
    margin: 0;
    padding: 0;
    font-size: 50px
}

#modal-wrapper{
    display: none;
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.116);
    text-align: center;
}

#modal-body{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 400px;
    height: 300px;
    background-color: seashell;
}


.active-modal{
    display: block !important;
}

#content {
    background: white;
    height: 3000px;
}

Here the #modal-wrapper is fixed and display: none by default. And it also have .active-modal class which will be added when the user click the button. The active-modal class have the property of display:block, to make the modal visible on the web-page.

main.js :

var modal = document.getElementById('modal-wrapper');
modal.addEventListener('wheel', function(e) {
    e.preventDefault();
}, false);


function openModal(){
    fixed.classList.add("active-modal");
}


function closeModal(){
    fixed.classList.remove("active-modal");
}

In the main.js file, all i have done is added an wheel event listen to #modal-wrapper and then disabled its default behaviour. So now when anyone try to use the mouse wheel to scroll the page the scroll will be disabled.

And it also have openModal() function , which will add active-modal class to #modal-wrappper and it will make the modal open on the screen.

The closeModal() function will remove the class from #modal-wrapper div. And the modal will be disappear.

You can disable the scrolling behaviour on a mobile device where we don't use a mouse wheel to scroll up and down a page, by following the instruction here: Disable Scroll in Mobile Device

https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event


💾 Recommended Articles