javascriptreactjsdomnext.jsfrontend

Unable to freeze the scroll after setting body.overflow to hidden in Next Js


I am having this issue in my Nextjs where I am unable to freeze the page from scrolling even after I set the document.body.style.overflow to hidden.

This is the code: https://codesandbox.io/p/sandbox/gallant-leavitt-i0fz2c?file=%2Fpages%2Findex.tsx&selection=%5B%7B%22endColumn%22%3A28%2C%22endLineNumber%22%3A13%2C%22startColumn%22%3A27%2C%22startLineNumber%22%3A13%7D%5D

As you can see: In lines 11-14 where I click the freeze button, it disables scrolling. enter image description here

Result: The page is still scrollable.

Please let me know the solution to this.


Solution

  • You need to add position:fixed in addition to overflow:hidden

    document.body.style.cssText = "overflow: hidden; position:fixed;";
    

    Preventing scrolling will lose the scroll position. So, when scrolling is reenabled, it will reset the scroll position to the top of the page instead of where the user left off. To prevent this, you need to set the scrollTop position.

    const scrollTop = (document.documentElement || document.body).scrollTop;
    document.body.style.cssText = `overflow: hidden; position:fixed; margin-top: -${scrollTop}px;`; // add here to prevent shifting content on freeze
    

    On unfreezing, set the scroll top value to the original scroll top value before the freeze. Store it in state or a variable so it can be used later.

    const scrollTop = (document.documentElement || document.body).scrollTop; // original value to store in state or variable before freezing.
    
    //After unfreezing, set back to original value
    document.documentElement.scrollTop = scrollTop;
    document.body.scrollTop = scrollTop;