Prevent body from scrolling when a modal is opened

Here, in this article, we will learn 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 an eventListener. However, we can use the mousewheel and wheelevent, to stop the scroll on our webpage when the modal is 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 a 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 disabled 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 a 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 called Open Modal with a on click 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 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, que 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 clicks the button. The active-modal class has 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 add a wheel event listen to #modal-wrapper, and then disable its default behavior. So now when anyone tries to use the mouse wheel to scroll the page the scroll will be disabled.

And it also has openModal() function , which will add an 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 disappear.

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

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