How do you temporarily disable page scrolling using CSS and JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you temporarily disable page scrolling using CSS and JavaScript?

message-square
0

To temporarily disable page scrolling in JavaScript and CSS—such as while a modal dialog, drawer, or fullscreen overlay is open—toggle a overflow: hidden lock class on document.documentElement (<html>) or document.body, and when locking on position: fixed is needed (especially on mobile browsers), save window.scrollY, lock the body position cleanly, and restore the exact scroll position upon unlocking without triggering a smooth-scroll jump. Always use a reference counter (or guard) so opening two overlays at once does not prematurely re-enable scrolling when the first one closes.


1. CSS Scroll-Lock Class and Scrollbar Compensation

Define a dedicated lock class in CSS using overflow: hidden on html / body (and optionally scrollbar-gutter: stable on the scroll root to prevent layout shift when the vertical scrollbar disappears):

/* CSS snippet: lock page scroll cleanly and prevent horizontal/vertical shift */
html.scroll-locked,
body.scroll-locked {
  overflow: hidden;
  overscroll-behavior: none;
}

html {
  scrollbar-gutter: stable;
}
  • Use overscroll-behavior: none: Stops touch overscroll bounce or scroll chaining on mobile/trackpad devices while locked.
  • Avoid mutating inline style ad-hoc across many components: Centralizing the class name and state makes locking and unlocking predictable.

2. Reference-Counted JavaScript Scroll Lock Helper

Use a lock counter in JavaScript so multiple stacked modals or drawers can call lockPageScroll() and unlockPageScroll() independently without unlocking early while another overlay is still open:

// Reference-counted page scroll lock with defensive guards
const createScrollLocker = (lockClassName = "scroll-locked") => {
  if (typeof lockClassName !== "string" || lockClassName.trim().length === 0) {
    throw new TypeError("Expected lockClassName to be a non-empty string.");
  }

  let activeLocks = 0;
  let savedScrollY = 0;

  const applyLock = () => {
    if (typeof document === "undefined" || !document.body || !document.documentElement) {
      throw new Error("DOM document is not available.");
    }

    if (activeLocks === 0) {
      savedScrollY = typeof window !== "undefined" ? window.scrollY || window.pageYOffset || 0 : 0;
      document.documentElement.classList.add(lockClassName);
      document.body.classList.add(lockClassName);
    }

    activeLocks += 1;
    return activeLocks;
  };

  const releaseLock = () => {
    if (typeof document === "undefined" || !document.body || !document.documentElement) {
      return 0;
    }

    if (activeLocks <= 0) {
      activeLocks = 0;
      return 0;
    }

    activeLocks -= 1;

    if (activeLocks === 0) {
      document.documentElement.classList.remove(lockClassName);
      document.body.classList.remove(lockClassName);

      if (typeof window !== "undefined" && typeof window.scrollTo === "function") {
        try {
          window.scrollTo({ top: savedScrollY, left: 0, behavior: "instant" });
        } catch {
          window.scrollTo(0, savedScrollY);
        }
      }
    }

    return activeLocks;
  };

  return {
    lock: applyLock,
    unlock: releaseLock,
    getLockCount: () => activeLocks
  };
};

// Example usage:
try {
  const pageScroll = createScrollLocker("scroll-locked");
  pageScroll.lock();   // locks on first call (activeLocks === 1)
  pageScroll.unlock(); // restores scroll when activeLocks reaches 0
} catch (error) {
  console.error(`${error.name}: ${error.message}`);
}
  • Reference counting prevents premature unlock: Two modals open -> first closes (count = 1, still locked) -> second closes (count = 0, scroll restored).
  • Restore savedScrollY using "instant" behavior: Overrides any global html { scroll-behavior: smooth; } so closing a modal never animates back down the page.

3. Mobile Safari / iOS Fixed-Body Lock and Cleanup Gotchas

On some mobile browsers (especially iOS Safari), overflow: hidden alone may still allow rubber-band scrolling unless position: fixed, top: -${scrollY}px, and width: 100% are applied—and always release the lock in a cleanup path (modal close handler, route change, or finally block) so a thrown error never leaves the page permanently frozen:

// Lock scroll with fixed-body fallback for stubborn mobile viewports
function lockScrollStrict(state) {
  if (!state || typeof state !== "object") {
    throw new TypeError("Expected a mutable lock state object.");
  }
  if (typeof document === "undefined" || !document.body) {
    throw new Error("DOM body is unavailable.");
  }

  if (state.isLocked) {
    return;
  }

  const scrollY = typeof window !== "undefined" ? window.scrollY || 0 : 0;
  state.previousScrollY = scrollY;
  state.previousInlineStyle = {
    position: document.body.style.position,
    top: document.body.style.top,
    left: document.body.style.left,
    right: document.body.style.right,
    width: document.body.style.width,
    overflow: document.body.style.overflow
  };

  document.body.style.position = "fixed";
  document.body.style.top = `-${scrollY}px`;
  document.body.style.left = "0";
  document.body.style.right = "0";
  document.body.style.width = "100%";
  document.body.style.overflow = "hidden";
  state.isLocked = true;
}

function unlockScrollStrict(state) {
  if (!state || typeof state !== "object" || !state.isLocked) {
    return;
  }
  if (typeof document === "undefined" || !document.body) {
    return;
  }

  const prev = state.previousInlineStyle ?? {};
  document.body.style.position = prev.position ?? "";
  document.body.style.top = prev.top ?? "";
  document.body.style.left = prev.left ?? "";
  document.body.style.right = prev.right ?? "";
  document.body.style.width = prev.width ?? "";
  document.body.style.overflow = prev.overflow ?? "";

  const restoreY = typeof state.previousScrollY === "number" ? state.previousScrollY : 0;
  state.isLocked = false;

  if (typeof window !== "undefined" && typeof window.scrollTo === "function") {
    window.scrollTo(0, restoreY);
  }
}

// Example usage:
const mobileLockState = { isLocked: false, previousScrollY: 0, previousInlineStyle: null };
try {
  lockScrollStrict(mobileLockState);
  // ... modal open logic ...
} finally {
  unlockScrollStrict(mobileLockState);
}
  • Always clean up on unmount or error: An un-released scroll lock traps users unable to scroll the page, especially on mobile.
  • Avoid locking document.body while also locking a nested scroll container inside the modal: Keep inner modal content scrollable (overflow-y: auto) while locking only the outer page background.