DocsHover & overlays
Get started

Search Subtly documentation

Search by a task, helper name or framework.

Hover & overlays

lockScroll()

Stop the page moving behind a dialog.

Try the example

Open the sample dialog and try scrolling the page behind it. Close the dialog to restore page scrolling. Escape also closes it.

Overlay behaviorKeep the page in place

Scroll the page a little before opening to check that its position is preserved.

A focused moment

The page behind this dialog is locked. The dialog uses native modal focus behavior.

Page scrolling is available.

Actual npm package · local demonstration

Add it to your project

  1. Copy the HTML. Place the markup inside the component where this behavior belongs. The preview’s visual classes are website styles; use your own design system.
  2. Connect the behavior. Copy the JavaScript tab and call its exported mount(element) after your component’s elements exist. Replace simulated delays and data operations with your own application code.
  3. Clean up. Call the returned cleanup when the component unmounts. It aborts the example’s listeners and releases the helper’s timers, observers or state.

API and lifecycle

Call lockScroll() when an overlay needs to stop body scrolling. It saves the previous body styles and scroll position, accounts for scrollbar width, and returns a release function.

Interface
returns idempotent release callback
Lifecycle
Locks are reference-counted: each caller must release its own lock. Releasing the same callback twice is safe; the original scroll state returns after the last lock is released.

Accessibility and safety

Implementation notes

Avoid double scroll locking with modal libraries; test on iOS Safari.

Do not apply a second lock when your modal library already provides one. Scroll locking does not manage focus or make the background inert.

What to check

Open and close nested overlays, release each lock, and check the original scroll position returns. Test iOS Safari and content inside the overlay.