javascriptjqueryhtmlcss

How to disable scroll without hiding it?


I'm trying to disable the html/body scrollbar of the parent while I'm using a lightbox. The main word here is disable. I do not want to hide it with overflow: hidden;.

The reason for this is that overflow: hidden makes the site jump and take up the area where the scroll was.

I want to know if its possible to disable a scrollbar while still showing it.


Solution

  • If the page under the overlayer can be "fixed" at the top, when you open the overlay you can set

    body { 
      position: fixed; 
      overflow-y: scroll;
    }
    

    you should still see the right scrollbar but the content is not scrollable. When you close the overlay just revert these properties with

    body { 
      position: static;
      overflow-y: auto; 
    }
    

    I just proposed this way only because you wouldn't need to change any scroll event

    What if I already scrolled the page?

    if you get the document.documentElement.scrollTop property via javascript just before the layer opening, you could dynamically assign that value as top property of the body element: with this approach the page will keep its current scroll position, no matter if you're on top or if you have already scrolled.

    Css

    .noscroll {
      position: fixed; 
      top: var(--st, 0);
      inline-size: 100%;
      overflow-y:scroll; 
    }
    

    JS

    const b = document.body;
    b.style.setProperty('--st', -(document.documentElement.scrollTop) + "px");
    b.classList.add('noscroll');