How to disable page scrolling?
1. The simplest and most reliable way - via CSS (overflow: hidden)
The browser lets you disable scrolling for the whole page
by setting overflow: hidden on <body> (or <html>).
document.body.style.overflow = 'hidden'; // disable scrollTo restore it:
document.body.style.overflow = ''; // re-enable scrollThis is the most common approach - the page stays in place, and both the mouse wheel and touch scroll stop working.
2. A convenient function to toggle scrolling
function disableScroll() {
document.body.style.overflow = 'hidden';
}
function enableScroll() {
document.body.style.overflow = '';
}Usage:
openModalBtn.addEventListener('click', disableScroll);
closeModalBtn.addEventListener('click', enableScroll);3. A more advanced way - preserve the position (so it does not "jump")
If the page was already scrolled and you just apply overflow: hidden,
the content can jerk because the scrollbar disappears.
Here is the correct way, with position fixing:
function disableScroll() {
const scrollY = window.scrollY;
document.body.style.position = 'fixed';
document.body.style.top = `-${scrollY}px`;
document.body.style.width = '100%';
}
function enableScroll() {
const scrollY = document.body.style.top;
document.body.style.position = '';
document.body.style.top = '';
window.scrollTo(0, parseInt(scrollY || '0') * -1);
}Now the page stays exactly where the user left it, and returns there after unlocking.
4. An alternative - a CSS class
Convenient if you open modals often:
/* styles.css */
.no-scroll {
overflow: hidden;
}document.body.classList.add('no-scroll'); // lock
document.body.classList.remove('no-scroll'); // unlockClean, convenient, and easy to scale.
5. A special case - blocking scroll on mobile devices
On iOS, overflow: hidden sometimes does not help with touch scrolling inside <body>.
In that case, intercepting touchmove is used:
function preventTouchScroll(e) {
e.preventDefault();
}
function disableScrollMobile() {
document.addEventListener('touchmove', preventTouchScroll, { passive: false });
}
function enableScrollMobile() {
document.removeEventListener('touchmove', preventTouchScroll);
}This approach can be combined with overflow: hidden for reliability.
Summary
| Goal | Method | Note |
|---|---|---|
| Simply disable it | document.body.style.overflow = 'hidden' | Works for 95% of cases |
| Preserve the position | position: fixed + top = -scrollY | No "jump" when unlocking |
| Frequent use | Adding the .no-scroll class | Convenient for modals |
| Mobile reliability | touchmove + preventDefault | For iOS Safari |
Simple rule of thumb:
overflow: hiddendisables scrolling,position: fixedfixes the position,touchmove.preventDefault()guards against touch scrolling on mobile.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.