Locks that nest
A drawer opens a dialog that opens a menu: each holds its own lock, and the page unlocks after the last one, in any order.
Mark a dialog with data-scroll-lock, or call lockScroll(), and the page behind it stops scrolling without jumping sideways, even on iPhone.
Install it, try the live preview, then read the full reference.
npm install @samline/scroll-lockAbout 3.8 KB gzipZero dependenciesMIT licensed
ONE SMALL SCRIPT. RIGHT AT HOME IN YOUR STACK.
A drawer opens a dialog that opens a menu: each holds its own lock, and the page unlocks after the last one, in any order.
The scrollbar width moves to the body padding and to --scroll-lock-gap, so content and fixed headers stay where they were.
The scroll position survives the lock, and comes back at once on release, even with scroll-behavior: smooth.
Mobile Safari ignores overflow: hidden. On iOS the lock blocks page touches and keeps inputs above the keyboard instead.
data-scroll-lock on a dialog, details, popover or any element locks while it is open and releases when it closes or leaves.
data-scroll-lock-state marks the locked page and each element that holds a lock, ready for backdrops and transitions.
Without JavaScript the page simply keeps scrolling; nothing breaks.
Package
lockScroll, createScrollLock, scrollLock and autoScrollLock as ESM or CommonJS.
One lock
Returns the release, safe to call twice.
Whole page
Every [data-scroll-lock], including elements added later.
HTML / CDN
A classic script that starts on its own.
Per component
lock, unlock and toggle without double releases.
Styling
Style the locked page with data-scroll-lock-state.
Lock the page behind a modal dialog while it is open.
Read the installation guideInstall
npm
npm install @samline/scroll-lockpnpm
pnpm add @samline/scroll-lockyarn
yarn add @samline/scroll-lockbun
bun add @samline/scroll-lockHTML / CDN
<script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js" defer></script>Mark the dialog
data-scroll-lock on a dialog, details, popover or any element that shows and hides.
<button type="button" id="open">Read the terms</button>
<dialog id="terms" data-scroll-lock>
<p>…</p>
<form method="dialog"><button>Close</button></form>
</dialog>Start it
import { autoScrollLock } from '@samline/scroll-lock'
autoScrollLock()
document.querySelector('#open').addEventListener('click', () => {
document.querySelector('#terms').showModal()
})Continue with every option, the attributes and how iOS is handled.
Explore the optionsThree common jobs, without touching overflow yourself.
const unlock = lockScroll()
drawer.addEventListener('close', unlock, { once: true }).header {
padding-right: var(--scroll-lock-gap, 0px);
}const lock = createScrollLock()
button.addEventListener('click', () => {
menu.hidden = !menu.hidden
lock.toggle(!menu.hidden)
})Try the examples or follow the first steps.
Guides, the complete API and release notes, in one place.
Read the documentation