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
.
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.
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;