Disable scrolling Behavior on a body with element on position fixed in mobile

Here in this article, we will learn on how to disable the scroll behavior of the body whenever we scroll over an element whose position is fixed in our mobile devices.

To get the results we just have to add some JavaScript to disable the default scrolling behavior.

Suppose we have we have two div one with id content and the other with id fixed. The div with id fixed have position:fixed as a CSS property.

Now we want that, whenever we are over the fixed div and scroll, the body or the content div should not scroll up or down.

Disable the default scrolling behaviour on fixed element.

To disable the default scrolling behavior we will add a addEventListener() to the div with id fixed and prevent the default scrolling.

Note: We will be using eventListener touchmove, to listen to the event triggered when we touch the particular fixed element on our mobile device.

HTML Code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Disable scroll on fixed element on mobile</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
      <div id="fixed">
      </div>
    <div id="content">
      Lorem ipsum dolor sit, amet consectetur adipisicing elit. Corrupti accusamus sequi quibusdam deserunt voluptas inventore incidunt optio sit reiciendis ipsam temporibus eveniet sunt aperiam impedit, sed tempore neque ex reprehenderit ullam. Doloribus nostrum, odit nobis aliquid, nam soluta nesciunt ullam, veniam nihil voluptatem dolor minus reprehenderit? Voluptates quisquam dolorem sunt excepturi nostrum iusto aut quaerat nisi doloribus aperiam nemo ipsum, ullam dolores deleniti magni deserunt aliquid quos sit eius quae error, optio commodi! Obcaecati pariatur voluptate asperiores debitis, quae id in perferendis alias ipsa blanditiis incidunt fugiat itaque corporis molestiae voluptas, accusantium ipsam provident, fuga corrupti sapiente! Ex, tempore.
    </div>
    <script src="script.js"></script>
  </body>
</html>

CSS style:

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

#fixed {
    background: red;
    position: fixed;
    left:0;
    top: 0;
    bottom: 0;
    right: 0;
    width: 200px;
    height: 100%;
    z-index: 3;
}

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

script.js :

var fixed = document.getElementById('fixed');
fixed.addEventListener('touchmove', function(e) {
    e.preventDefault();
}, false);

NOTE : Check the behaviour on your mobile devices , in desktop you will not get the results.

So in script.js file we have prevented the scroll behaviour of the fixed element on mobile devices. So now if you try to scroll using your finger, the content will not move up or down.

Scroll to Top