Skip to main content

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

javascript
document.body.style.overflow = 'hidden'; // disable scroll

To restore it:

javascript
document.body.style.overflow = ''; // re-enable scroll

This 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

javascript
function disableScroll() { document.body.style.overflow = 'hidden'; } function enableScroll() { document.body.style.overflow = ''; }

Usage:

javascript
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:

javascript
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:

javascript
/* styles.css */ .no-scroll { overflow: hidden; }
javascript
document.body.classList.add('no-scroll'); // lock document.body.classList.remove('no-scroll'); // unlock

Clean, 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:

javascript
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

GoalMethodNote
Simply disable itdocument.body.style.overflow = 'hidden'Works for 95% of cases
Preserve the positionposition: fixed + top = -scrollYNo "jump" when unlocking
Frequent useAdding the .no-scroll classConvenient for modals
Mobile reliabilitytouchmove + preventDefaultFor iOS Safari

Simple rule of thumb: overflow: hidden disables scrolling, position: fixed fixes the position, touchmove.preventDefault() guards against touch scrolling on mobile.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.