Guide

Working examples

Every live Scroll Lock preview with its explanation and the complete, copyable source files of each one.

Each preview is the same one shown on Home and Examples, and runs the real package: it locks this page. The copied files load the published browser bundle, so they work as they are.

Lock the page behind a modal dialog

Modal dialogLive preview

data-scroll-lock on the dialog locks the page while it is open and releases it however it closes: the close button, the form, Escape or a click outside. The list inside still scrolls.

Page scrolls

Terms

Clause 1. This list scrolls; the page behind it does not.

Clause 2. This list scrolls; the page behind it does not.

Clause 3. This list scrolls; the page behind it does not.

Clause 4. This list scrolls; the page behind it does not.

Clause 5. This list scrolls; the page behind it does not.

Clause 6. This list scrolls; the page behind it does not.

Clause 7. This list scrolls; the page behind it does not.

Clause 8. This list scrolls; the page behind it does not.

Clause 9. This list scrolls; the page behind it does not.

Clause 10. This list scrolls; the page behind it does not.

Clause 11. This list scrolls; the page behind it does not.

Clause 12. This list scrolls; the page behind it does not.

Close with the button, Escape or a click outside.

Explore the code

HTML / CDN

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock the page behind a modal dialog</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <button type="button" id="open" aria-haspopup="dialog">Read the terms</button>
      <dialog id="terms" data-scroll-lock closedby="any" aria-labelledby="terms-title">
        <div class="header">
          <h2 id="terms-title">Terms</h2>
          <form method="dialog">
            <button class="close" aria-label="Close the terms">
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                <path
                  d="M6 6l12 12M18 6L6 18"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                />
              </svg>
            </button>
          </form>
        </div>
        <div class="list" tabindex="0" role="region" aria-label="Clauses">
          <p>Clause 1.</p>
          <p>Clause 2.</p>
          <p>Clause 3.</p>
          <p>Clause 4.</p>
          <p>Clause 5.</p>
          <p>Clause 6.</p>
          <p>Clause 7.</p>
          <p>Clause 8.</p>
          <p>Clause 9.</p>
          <p>Clause 10.</p>
          <p>Clause 11.</p>
          <p>Clause 12.</p>
        </div>
        <form method="dialog"><button>Accept</button></form>
      </dialog>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js"></script>
    <script src="./main.js" defer></script>
  </body>
</html>

CSS

style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
}
.page {
  padding: 1rem 1.5rem;
}
section {
  min-height: 60vh;
  border-top: 1px solid #ddd;
}
.close {
  display: grid;
  place-items: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ddd;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
#open {
  position: fixed;
  top: 1rem;
  right: 1rem;
}
dialog {
  width: min(28rem, calc(100vw - 2rem));
  box-sizing: border-box;
}
dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
}
.list {
  max-height: 12rem;
  overflow-y: auto;
  overscroll-behavior: contain;
}

JavaScript

main.js
// The bundle already watches [data-scroll-lock].
const dialog = document.querySelector('#terms')

document.querySelector('#open').addEventListener('click', () => dialog.showModal())

// Light dismiss where closedby="any" is not supported yet (Safari).
if (!('closedBy' in HTMLDialogElement.prototype)) {
  dialog.addEventListener('click', event => {
    if (event.target !== dialog) return
    const box = dialog.getBoundingClientRect()
    const inside =
      event.clientX >= box.left &&
      event.clientX <= box.right &&
      event.clientY >= box.top &&
      event.clientY <= box.bottom
    if (!inside) dialog.close()
  })
}

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock the page behind a modal dialog</title>
    <style>
      body {
        margin: 0;
        font-family: system-ui, sans-serif;
      }
      .page {
        padding: 1rem 1.5rem;
      }
      section {
        min-height: 60vh;
        border-top: 1px solid #ddd;
      }
      .close {
        display: grid;
        place-items: center;
        width: 2rem;
        height: 2rem;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
      }
      #open {
        position: fixed;
        top: 1rem;
        right: 1rem;
      }
      dialog {
        width: min(28rem, calc(100vw - 2rem));
        box-sizing: border-box;
      }
      dialog::backdrop {
        background: rgb(0 0 0 / 0.4);
      }
      .list {
        max-height: 12rem;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    </style>
  </head>
  <body>
    <main>
      <button type="button" id="open" aria-haspopup="dialog">Read the terms</button>
      <dialog id="terms" data-scroll-lock closedby="any" aria-labelledby="terms-title">
        <div class="header">
          <h2 id="terms-title">Terms</h2>
          <form method="dialog">
            <button class="close" aria-label="Close the terms">
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                <path
                  d="M6 6l12 12M18 6L6 18"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                />
              </svg>
            </button>
          </form>
        </div>
        <div class="list" tabindex="0" role="region" aria-label="Clauses">
          <p>Clause 1.</p>
          <p>Clause 2.</p>
          <p>Clause 3.</p>
          <p>Clause 4.</p>
          <p>Clause 5.</p>
          <p>Clause 6.</p>
          <p>Clause 7.</p>
          <p>Clause 8.</p>
          <p>Clause 9.</p>
          <p>Clause 10.</p>
          <p>Clause 11.</p>
          <p>Clause 12.</p>
        </div>
        <form method="dialog"><button>Accept</button></form>
      </dialog>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js"></script>
    <script>
      // The bundle already watches [data-scroll-lock].
      const dialog = document.querySelector('#terms')

      document.querySelector('#open').addEventListener('click', () => dialog.showModal())

      // Light dismiss where closedby="any" is not supported yet (Safari).
      if (!('closedBy' in HTMLDialogElement.prototype)) {
        dialog.addEventListener('click', event => {
          if (event.target !== dialog) return
          const box = dialog.getBoundingClientRect()
          const inside =
            event.clientX >= box.left &&
            event.clientX <= box.right &&
            event.clientY >= box.top &&
            event.clientY <= box.bottom
          if (!inside) dialog.close()
        })
      }
    </script>
  </body>
</html>

Package / ESM

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock the page behind a modal dialog</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <button type="button" id="open" aria-haspopup="dialog">Read the terms</button>
      <dialog id="terms" data-scroll-lock closedby="any" aria-labelledby="terms-title">
        <div class="header">
          <h2 id="terms-title">Terms</h2>
          <form method="dialog">
            <button class="close" aria-label="Close the terms">
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                <path
                  d="M6 6l12 12M18 6L6 18"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                />
              </svg>
            </button>
          </form>
        </div>
        <div class="list" tabindex="0" role="region" aria-label="Clauses">
          <p>Clause 1.</p>
          <p>Clause 2.</p>
          <p>Clause 3.</p>
          <p>Clause 4.</p>
          <p>Clause 5.</p>
          <p>Clause 6.</p>
          <p>Clause 7.</p>
          <p>Clause 8.</p>
          <p>Clause 9.</p>
          <p>Clause 10.</p>
          <p>Clause 11.</p>
          <p>Clause 12.</p>
        </div>
        <form method="dialog"><button>Accept</button></form>
      </dialog>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script type="module" src="./main.js"></script>
  </body>
</html>

CSS

style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
}
.page {
  padding: 1rem 1.5rem;
}
section {
  min-height: 60vh;
  border-top: 1px solid #ddd;
}
.close {
  display: grid;
  place-items: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ddd;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
#open {
  position: fixed;
  top: 1rem;
  right: 1rem;
}
dialog {
  width: min(28rem, calc(100vw - 2rem));
  box-sizing: border-box;
}
dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
}
.list {
  max-height: 12rem;
  overflow-y: auto;
  overscroll-behavior: contain;
}

JavaScript

main.js
import { autoScrollLock } from '@samline/scroll-lock'

autoScrollLock()

const dialog = document.querySelector('#terms')

document.querySelector('#open').addEventListener('click', () => dialog.showModal())

// Light dismiss where closedby="any" is not supported yet (Safari).
if (!('closedBy' in HTMLDialogElement.prototype)) {
  dialog.addEventListener('click', event => {
    if (event.target !== dialog) return
    const box = dialog.getBoundingClientRect()
    const inside =
      event.clientX >= box.left &&
      event.clientX <= box.right &&
      event.clientY >= box.top &&
      event.clientY <= box.bottom
    if (!inside) dialog.close()
  })
}

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock the page behind a modal dialog</title>
    <style>
      body {
        margin: 0;
        font-family: system-ui, sans-serif;
      }
      .page {
        padding: 1rem 1.5rem;
      }
      section {
        min-height: 60vh;
        border-top: 1px solid #ddd;
      }
      .close {
        display: grid;
        place-items: center;
        width: 2rem;
        height: 2rem;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
      }
      #open {
        position: fixed;
        top: 1rem;
        right: 1rem;
      }
      dialog {
        width: min(28rem, calc(100vw - 2rem));
        box-sizing: border-box;
      }
      dialog::backdrop {
        background: rgb(0 0 0 / 0.4);
      }
      .list {
        max-height: 12rem;
        overflow-y: auto;
        overscroll-behavior: contain;
      }
    </style>
  </head>
  <body>
    <main>
      <button type="button" id="open" aria-haspopup="dialog">Read the terms</button>
      <dialog id="terms" data-scroll-lock closedby="any" aria-labelledby="terms-title">
        <div class="header">
          <h2 id="terms-title">Terms</h2>
          <form method="dialog">
            <button class="close" aria-label="Close the terms">
              <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
                <path
                  d="M6 6l12 12M18 6L6 18"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                />
              </svg>
            </button>
          </form>
        </div>
        <div class="list" tabindex="0" role="region" aria-label="Clauses">
          <p>Clause 1.</p>
          <p>Clause 2.</p>
          <p>Clause 3.</p>
          <p>Clause 4.</p>
          <p>Clause 5.</p>
          <p>Clause 6.</p>
          <p>Clause 7.</p>
          <p>Clause 8.</p>
          <p>Clause 9.</p>
          <p>Clause 10.</p>
          <p>Clause 11.</p>
          <p>Clause 12.</p>
        </div>
        <form method="dialog"><button>Accept</button></form>
      </dialog>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script type="module">
      import { autoScrollLock } from '@samline/scroll-lock'

      autoScrollLock()

      const dialog = document.querySelector('#terms')

      document.querySelector('#open').addEventListener('click', () => dialog.showModal())

      // Light dismiss where closedby="any" is not supported yet (Safari).
      if (!('closedBy' in HTMLDialogElement.prototype)) {
        dialog.addEventListener('click', event => {
          if (event.target !== dialog) return
          const box = dialog.getBoundingClientRect()
          const inside =
            event.clientX >= box.left &&
            event.clientX <= box.right &&
            event.clientY >= box.top &&
            event.clientY <= box.bottom
          if (!inside) dialog.close()
        })
      }
    </script>
  </body>
</html>

Open several panels, unlock in any order

Nested locksLive preview

Each side panel holds its own lock with createScrollLock. The page stays locked until the last one closes, whichever order you close them in (button or Escape), and returns to the same scroll position.

Page scrolls
Explore the code

HTML / CDN

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Open several panels, unlock in any order</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <div class="toolbar">
        <button type="button" aria-expanded="false" aria-controls="cart">Cart</button>
        <button type="button" aria-expanded="false" aria-controls="filters">Filters</button>
        <output id="status" aria-live="polite">Page scrolls</output>
      </div>
      <aside class="panel" id="cart" popover="manual" aria-labelledby="cart-title">
        <div class="header">
          <h2 id="cart-title">Cart</h2>
          <button type="button" class="close" aria-label="Close cart">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <aside class="panel" id="filters" popover="manual" aria-labelledby="filters-title">
        <div class="header">
          <h2 id="filters-title">Filters</h2>
          <button type="button" class="close" aria-label="Close filters">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js"></script>
    <script src="./main.js" defer></script>
  </body>
</html>

CSS

style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
}
.page {
  padding: 1rem 1.5rem;
}
section {
  min-height: 60vh;
  border-top: 1px solid #ddd;
}
.close {
  display: grid;
  place-items: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ddd;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
.toolbar {
  position: fixed;
  inset: 0 0 auto;
  z-index: 1;
  display: flex;
  gap: 0.5rem;
  align-items: center;
  padding: 0.75rem 1rem;
  padding-right: calc(1rem + var(--scroll-lock-gap, 0px));
  background: #fff;
  border-bottom: 1px solid #ddd;
}
[aria-expanded='true'] {
  background: #2563eb;
  color: #fff;
}
/* Below the toolbar, so both buttons stay in reach. */
.panel {
  position: fixed;
  inset: 3.5rem auto 0;
  width: min(18rem, calc(100vw - 3rem));
  height: auto;
  margin: 0;
  padding: 1rem;
  box-sizing: border-box;
  border: 0;
  background: #fff;
  box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
}
#cart {
  right: 0;
}
#filters {
  left: 0;
}
.page {
  padding-top: 4rem;
}

JavaScript

main.js
// ScrollLock comes from the browser bundle.
const status = document.querySelector('#status')
const open = [] // Most recently opened last, so Escape closes the top panel first.

const report = () => {
  status.textContent = ScrollLock.isScrollLocked()
    ? `Page locked, ${open.length} ${open.length === 1 ? 'panel' : 'panels'} open`
    : 'Page scrolls'
}

for (const button of document.querySelectorAll('[aria-controls]')) {
  const panel = document.getElementById(button.getAttribute('aria-controls'))
  const lock = ScrollLock.createScrollLock()
  const set = wanted => {
    lock.toggle(wanted)
    panel.togglePopover(wanted)
    button.setAttribute('aria-expanded', String(wanted))
    if (open.includes(close)) open.splice(open.indexOf(close), 1)
    if (wanted) open.push(close)
    report()
  }
  const close = () => set(false)
  button.addEventListener('click', () => set(!lock.isLocked()))
  panel.querySelector('.close').addEventListener('click', close)
}

document.addEventListener('keydown', event => {
  if (event.key === 'Escape' && open.length) open.at(-1)()
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Open several panels, unlock in any order</title>
    <style>
      body {
        margin: 0;
        font-family: system-ui, sans-serif;
      }
      .page {
        padding: 1rem 1.5rem;
      }
      section {
        min-height: 60vh;
        border-top: 1px solid #ddd;
      }
      .close {
        display: grid;
        place-items: center;
        width: 2rem;
        height: 2rem;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
      }
      .toolbar {
        position: fixed;
        inset: 0 0 auto;
        z-index: 1;
        display: flex;
        gap: 0.5rem;
        align-items: center;
        padding: 0.75rem 1rem;
        padding-right: calc(1rem + var(--scroll-lock-gap, 0px));
        background: #fff;
        border-bottom: 1px solid #ddd;
      }
      [aria-expanded='true'] {
        background: #2563eb;
        color: #fff;
      }
      /* Below the toolbar, so both buttons stay in reach. */
      .panel {
        position: fixed;
        inset: 3.5rem auto 0;
        width: min(18rem, calc(100vw - 3rem));
        height: auto;
        margin: 0;
        padding: 1rem;
        box-sizing: border-box;
        border: 0;
        background: #fff;
        box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
      }
      #cart {
        right: 0;
      }
      #filters {
        left: 0;
      }
      .page {
        padding-top: 4rem;
      }
    </style>
  </head>
  <body>
    <main>
      <div class="toolbar">
        <button type="button" aria-expanded="false" aria-controls="cart">Cart</button>
        <button type="button" aria-expanded="false" aria-controls="filters">Filters</button>
        <output id="status" aria-live="polite">Page scrolls</output>
      </div>
      <aside class="panel" id="cart" popover="manual" aria-labelledby="cart-title">
        <div class="header">
          <h2 id="cart-title">Cart</h2>
          <button type="button" class="close" aria-label="Close cart">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <aside class="panel" id="filters" popover="manual" aria-labelledby="filters-title">
        <div class="header">
          <h2 id="filters-title">Filters</h2>
          <button type="button" class="close" aria-label="Close filters">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js"></script>
    <script>
      // ScrollLock comes from the browser bundle.
      const status = document.querySelector('#status')
      const open = [] // Most recently opened last, so Escape closes the top panel first.

      const report = () => {
        status.textContent = ScrollLock.isScrollLocked()
          ? `Page locked, ${open.length} ${open.length === 1 ? 'panel' : 'panels'} open`
          : 'Page scrolls'
      }

      for (const button of document.querySelectorAll('[aria-controls]')) {
        const panel = document.getElementById(button.getAttribute('aria-controls'))
        const lock = ScrollLock.createScrollLock()
        const set = wanted => {
          lock.toggle(wanted)
          panel.togglePopover(wanted)
          button.setAttribute('aria-expanded', String(wanted))
          if (open.includes(close)) open.splice(open.indexOf(close), 1)
          if (wanted) open.push(close)
          report()
        }
        const close = () => set(false)
        button.addEventListener('click', () => set(!lock.isLocked()))
        panel.querySelector('.close').addEventListener('click', close)
      }

      document.addEventListener('keydown', event => {
        if (event.key === 'Escape' && open.length) open.at(-1)()
      })
    </script>
  </body>
</html>

Package / ESM

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Open several panels, unlock in any order</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <div class="toolbar">
        <button type="button" aria-expanded="false" aria-controls="cart">Cart</button>
        <button type="button" aria-expanded="false" aria-controls="filters">Filters</button>
        <output id="status" aria-live="polite">Page scrolls</output>
      </div>
      <aside class="panel" id="cart" popover="manual" aria-labelledby="cart-title">
        <div class="header">
          <h2 id="cart-title">Cart</h2>
          <button type="button" class="close" aria-label="Close cart">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <aside class="panel" id="filters" popover="manual" aria-labelledby="filters-title">
        <div class="header">
          <h2 id="filters-title">Filters</h2>
          <button type="button" class="close" aria-label="Close filters">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script type="module" src="./main.js"></script>
  </body>
</html>

CSS

style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
}
.page {
  padding: 1rem 1.5rem;
}
section {
  min-height: 60vh;
  border-top: 1px solid #ddd;
}
.close {
  display: grid;
  place-items: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ddd;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
.toolbar {
  position: fixed;
  inset: 0 0 auto;
  z-index: 1;
  display: flex;
  gap: 0.5rem;
  align-items: center;
  padding: 0.75rem 1rem;
  padding-right: calc(1rem + var(--scroll-lock-gap, 0px));
  background: #fff;
  border-bottom: 1px solid #ddd;
}
[aria-expanded='true'] {
  background: #2563eb;
  color: #fff;
}
/* Below the toolbar, so both buttons stay in reach. */
.panel {
  position: fixed;
  inset: 3.5rem auto 0;
  width: min(18rem, calc(100vw - 3rem));
  height: auto;
  margin: 0;
  padding: 1rem;
  box-sizing: border-box;
  border: 0;
  background: #fff;
  box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
}
#cart {
  right: 0;
}
#filters {
  left: 0;
}
.page {
  padding-top: 4rem;
}

JavaScript

main.js
import { createScrollLock, isScrollLocked } from '@samline/scroll-lock'

const status = document.querySelector('#status')
const open = [] // Most recently opened last, so Escape closes the top panel first.

const report = () => {
  status.textContent = isScrollLocked()
    ? `Page locked, ${open.length} ${open.length === 1 ? 'panel' : 'panels'} open`
    : 'Page scrolls'
}

for (const button of document.querySelectorAll('[aria-controls]')) {
  const panel = document.getElementById(button.getAttribute('aria-controls'))
  const lock = createScrollLock()
  const set = wanted => {
    lock.toggle(wanted)
    panel.togglePopover(wanted)
    button.setAttribute('aria-expanded', String(wanted))
    if (open.includes(close)) open.splice(open.indexOf(close), 1)
    if (wanted) open.push(close)
    report()
  }
  const close = () => set(false)
  button.addEventListener('click', () => set(!lock.isLocked()))
  panel.querySelector('.close').addEventListener('click', close)
}

document.addEventListener('keydown', event => {
  if (event.key === 'Escape' && open.length) open.at(-1)()
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Open several panels, unlock in any order</title>
    <style>
      body {
        margin: 0;
        font-family: system-ui, sans-serif;
      }
      .page {
        padding: 1rem 1.5rem;
      }
      section {
        min-height: 60vh;
        border-top: 1px solid #ddd;
      }
      .close {
        display: grid;
        place-items: center;
        width: 2rem;
        height: 2rem;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
      }
      .toolbar {
        position: fixed;
        inset: 0 0 auto;
        z-index: 1;
        display: flex;
        gap: 0.5rem;
        align-items: center;
        padding: 0.75rem 1rem;
        padding-right: calc(1rem + var(--scroll-lock-gap, 0px));
        background: #fff;
        border-bottom: 1px solid #ddd;
      }
      [aria-expanded='true'] {
        background: #2563eb;
        color: #fff;
      }
      /* Below the toolbar, so both buttons stay in reach. */
      .panel {
        position: fixed;
        inset: 3.5rem auto 0;
        width: min(18rem, calc(100vw - 3rem));
        height: auto;
        margin: 0;
        padding: 1rem;
        box-sizing: border-box;
        border: 0;
        background: #fff;
        box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
      }
      #cart {
        right: 0;
      }
      #filters {
        left: 0;
      }
      .page {
        padding-top: 4rem;
      }
    </style>
  </head>
  <body>
    <main>
      <div class="toolbar">
        <button type="button" aria-expanded="false" aria-controls="cart">Cart</button>
        <button type="button" aria-expanded="false" aria-controls="filters">Filters</button>
        <output id="status" aria-live="polite">Page scrolls</output>
      </div>
      <aside class="panel" id="cart" popover="manual" aria-labelledby="cart-title">
        <div class="header">
          <h2 id="cart-title">Cart</h2>
          <button type="button" class="close" aria-label="Close cart">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <aside class="panel" id="filters" popover="manual" aria-labelledby="filters-title">
        <div class="header">
          <h2 id="filters-title">Filters</h2>
          <button type="button" class="close" aria-label="Close filters">
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
      </aside>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script type="module">
      import { createScrollLock, isScrollLocked } from '@samline/scroll-lock'

      const status = document.querySelector('#status')
      const open = [] // Most recently opened last, so Escape closes the top panel first.

      const report = () => {
        status.textContent = isScrollLocked()
          ? `Page locked, ${open.length} ${open.length === 1 ? 'panel' : 'panels'} open`
          : 'Page scrolls'
      }

      for (const button of document.querySelectorAll('[aria-controls]')) {
        const panel = document.getElementById(button.getAttribute('aria-controls'))
        const lock = createScrollLock()
        const set = wanted => {
          lock.toggle(wanted)
          panel.togglePopover(wanted)
          button.setAttribute('aria-expanded', String(wanted))
          if (open.includes(close)) open.splice(open.indexOf(close), 1)
          if (wanted) open.push(close)
          report()
        }
        const close = () => set(false)
        button.addEventListener('click', () => set(!lock.isLocked()))
        panel.querySelector('.close').addEventListener('click', close)
      }

      document.addEventListener('keydown', event => {
        if (event.key === 'Escape' && open.length) open.at(-1)()
      })
    </script>
  </body>
</html>

Lock while a popover menu is open

Popover menuLive preview

A popover with data-scroll-lock locks the page from the moment it opens until it closes: the close button, a chosen link, Escape or a click outside. The lock needs no script of your own.

Page scrolls
Explore the code

HTML / CDN

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock while a popover menu is open</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <button type="button" popovertarget="menu">Menu</button>
      <nav id="menu" popover data-scroll-lock aria-labelledby="menu-title">
        <div class="header">
          <h2 id="menu-title">Menu</h2>
          <button
            type="button"
            class="close"
            popovertarget="menu"
            popovertargetaction="hide"
            aria-label="Close the menu"
          >
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
        <a href="#home">Home</a>
        <a href="#products">Products</a>
        <a href="#contact">Contact</a>
      </nav>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js"></script>
    <script src="./main.js" defer></script>
  </body>
</html>

CSS

style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
}
.page {
  padding: 1rem 1.5rem;
}
section {
  min-height: 60vh;
  border-top: 1px solid #ddd;
}
.close {
  display: grid;
  place-items: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ddd;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
[popovertarget='menu']:not(.close) {
  position: fixed;
  top: 1rem;
  right: 1rem;
}
#menu {
  position: fixed;
  inset: 0 0 0 auto;
  width: min(18rem, calc(100vw - 3rem));
  height: 100dvh;
  margin: 0;
  padding: 1rem;
  box-sizing: border-box;
  flex-direction: column;
  gap: 1rem;
  border: 0;
  box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
}
#menu:popover-open {
  display: flex;
}

JavaScript

main.js
// The bundle already watches [data-scroll-lock], popovers included.
const menu = document.querySelector('#menu')

// A chosen link closes the menu, which releases the lock.
menu.addEventListener('click', event => {
  if (event.target.closest('a')) menu.hidePopover()
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock while a popover menu is open</title>
    <style>
      body {
        margin: 0;
        font-family: system-ui, sans-serif;
      }
      .page {
        padding: 1rem 1.5rem;
      }
      section {
        min-height: 60vh;
        border-top: 1px solid #ddd;
      }
      .close {
        display: grid;
        place-items: center;
        width: 2rem;
        height: 2rem;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
      }
      [popovertarget='menu']:not(.close) {
        position: fixed;
        top: 1rem;
        right: 1rem;
      }
      #menu {
        position: fixed;
        inset: 0 0 0 auto;
        width: min(18rem, calc(100vw - 3rem));
        height: 100dvh;
        margin: 0;
        padding: 1rem;
        box-sizing: border-box;
        flex-direction: column;
        gap: 1rem;
        border: 0;
        box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
      }
      #menu:popover-open {
        display: flex;
      }
    </style>
  </head>
  <body>
    <main>
      <button type="button" popovertarget="menu">Menu</button>
      <nav id="menu" popover data-scroll-lock aria-labelledby="menu-title">
        <div class="header">
          <h2 id="menu-title">Menu</h2>
          <button
            type="button"
            class="close"
            popovertarget="menu"
            popovertargetaction="hide"
            aria-label="Close the menu"
          >
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
        <a href="#home">Home</a>
        <a href="#products">Products</a>
        <a href="#contact">Contact</a>
      </nav>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script src="https://cdn.jsdelivr.net/npm/@samline/scroll-lock@1.0.0/dist/browser/scroll-lock.global.js"></script>
    <script>
      // The bundle already watches [data-scroll-lock], popovers included.
      const menu = document.querySelector('#menu')

      // A chosen link closes the menu, which releases the lock.
      menu.addEventListener('click', event => {
        if (event.target.closest('a')) menu.hidePopover()
      })
    </script>
  </body>
</html>

Package / ESM

HTML

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock while a popover menu is open</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <main>
      <button type="button" popovertarget="menu">Menu</button>
      <nav id="menu" popover data-scroll-lock aria-labelledby="menu-title">
        <div class="header">
          <h2 id="menu-title">Menu</h2>
          <button
            type="button"
            class="close"
            popovertarget="menu"
            popovertargetaction="hide"
            aria-label="Close the menu"
          >
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
        <a href="#home">Home</a>
        <a href="#products">Products</a>
        <a href="#contact">Contact</a>
      </nav>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script type="module" src="./main.js"></script>
  </body>
</html>

CSS

style.css
body {
  margin: 0;
  font-family: system-ui, sans-serif;
}
.page {
  padding: 1rem 1.5rem;
}
section {
  min-height: 60vh;
  border-top: 1px solid #ddd;
}
.close {
  display: grid;
  place-items: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ddd;
  border-radius: 50%;
  background: #fff;
  cursor: pointer;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}
[popovertarget='menu']:not(.close) {
  position: fixed;
  top: 1rem;
  right: 1rem;
}
#menu {
  position: fixed;
  inset: 0 0 0 auto;
  width: min(18rem, calc(100vw - 3rem));
  height: 100dvh;
  margin: 0;
  padding: 1rem;
  box-sizing: border-box;
  flex-direction: column;
  gap: 1rem;
  border: 0;
  box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
}
#menu:popover-open {
  display: flex;
}

JavaScript

main.js
import { autoScrollLock } from '@samline/scroll-lock'

autoScrollLock()

const menu = document.querySelector('#menu')

// A chosen link closes the menu, which releases the lock.
menu.addEventListener('click', event => {
  if (event.target.closest('a')) menu.hidePopover()
})

Complete file

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Lock while a popover menu is open</title>
    <style>
      body {
        margin: 0;
        font-family: system-ui, sans-serif;
      }
      .page {
        padding: 1rem 1.5rem;
      }
      section {
        min-height: 60vh;
        border-top: 1px solid #ddd;
      }
      .close {
        display: grid;
        place-items: center;
        width: 2rem;
        height: 2rem;
        padding: 0;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
      }
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
      }
      [popovertarget='menu']:not(.close) {
        position: fixed;
        top: 1rem;
        right: 1rem;
      }
      #menu {
        position: fixed;
        inset: 0 0 0 auto;
        width: min(18rem, calc(100vw - 3rem));
        height: 100dvh;
        margin: 0;
        padding: 1rem;
        box-sizing: border-box;
        flex-direction: column;
        gap: 1rem;
        border: 0;
        box-shadow: 0 0 2rem rgb(0 0 0 / 0.2);
      }
      #menu:popover-open {
        display: flex;
      }
    </style>
  </head>
  <body>
    <main>
      <button type="button" popovertarget="menu">Menu</button>
      <nav id="menu" popover data-scroll-lock aria-labelledby="menu-title">
        <div class="header">
          <h2 id="menu-title">Menu</h2>
          <button
            type="button"
            class="close"
            popovertarget="menu"
            popovertargetaction="hide"
            aria-label="Close the menu"
          >
            <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true">
              <path
                d="M6 6l12 12M18 6L6 18"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
          </button>
        </div>
        <a href="#home">Home</a>
        <a href="#products">Products</a>
        <a href="#contact">Contact</a>
      </nav>
      <div class="page">
        <section><h2>Section 1</h2></section>
        <section><h2>Section 2</h2></section>
        <section><h2>Section 3</h2></section>
        <section><h2>Section 4</h2></section>
        <section><h2>Section 5</h2></section>
        <section><h2>Section 6</h2></section>
      </div>
    </main>
    <script type="module">
      import { autoScrollLock } from '@samline/scroll-lock'

      autoScrollLock()

      const menu = document.querySelector('#menu')

      // A chosen link closes the menu, which releases the lock.
      menu.addEventListener('click', event => {
        if (event.target.closest('a')) menu.hidePopover()
      })
    </script>
  </body>
</html>