Subtlyv0.1.1
Hover & overlays

lockScroll()

Stop the page moving behind a dialog. Nested overlays.

Available in v0.1.1scroll-lock.jsAccessibility

Try it

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

Live example
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.

<div id="your-component">
<div class="data-preview"><span class="muted">Overlay behavior</span><strong>Keep the page in place</strong><p>Scroll the page a little before opening to check that its position is preserved.</p></div><button data-open>Open sample dialog</button><dialog class="demo-dialog" aria-labelledby="scroll-dialog-title"><h3 id="scroll-dialog-title">A focused moment</h3><p>The page behind this dialog is locked. The dialog uses native modal focus behavior.</p><button data-close>Close dialog</button></dialog><p class="demo-status" role="status">Page scrolling is available.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const dialog = el.querySelector('dialog');
          let release;
          function unlock() {
            release?.(); release = undefined;
            status('Dialog closed. Page scrolling restored.');
          }
          el.querySelector('[data-open]').addEventListener('click', () => {
            release = kit.lockScroll();
            dialog.showModal();
            status('Dialog open. Page scrolling locked.');
          }, { signal });
          el.querySelector('[data-close]').addEventListener('click', () => dialog.close(), { signal });
          dialog.addEventListener('close', unlock, { signal });
          return () => { if (dialog.open) dialog.close(); unlock(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

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.

View documented module source
/** Reference-counted body scroll lock. Each caller must release its own lock.
 * Use only when the modal library does not already lock scrolling. */
let count=0, restore;
export function lockScroll(){
    if(count++===0){const body=document.body;const old=body.style.cssText;const x=window.scrollX,y=window.scrollY;const gap=window.innerWidth-document.documentElement.clientWidth;const padding=parseFloat(getComputedStyle(body).paddingRight)||0;
        Object.assign(body.style,{position:'fixed',top:`-${y}px`,left:`-${x}px`,width:'100%',boxSizing:'border-box',overflow:'hidden',paddingRight:`${padding+gap}px`});
        restore=()=>{body.style.cssText=old;window.scrollTo({left:x,top:y,behavior:'instant'});};
    }
    let released=false;return ()=>{if(released)return;released=true;if(--count===0){restore?.();restore=undefined;}};
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close