scroll-padlock

ScrollPadlock

Node.js CI scroll-padlock (latest) scroll-padlock (downloads) license

A small (~4K gzipped) unobtrusive script aimed to encourage a CSS-first approach when locking HTML elements scroll. The source code is entirely written in vanilla JavaScript with no dependencies.

Without:

without scrollbar gap compensation

With:

with scrollbar gap compensation

Examples

The HTML files in the “e2e” folder of the project can be used as demos to showcase how the library can be integrated with different approaches in various applications.

Inclusion

Node

npm install scroll-padlock
import { setScrollPadlockStyle } from "scroll-padlock";

setScrollPadlockStyle();

Browser modules

<script type="importmap">
  {
    "imports": {
      "scroll-padlock": "https://cdn.jsdelivr.net/npm/scroll-padlock@latest/+esm"
    }
  }
</script>

<script type="module">
  import { setScrollPadlockStyle } from "scroll-padlock";

  setScrollPadlockStyle();
</script>

Browser globals

<script src="https://cdn.jsdelivr.net/npm/scroll-padlock@latest/dist/scroll-padlock.umd.min.js"></script>

<script>
  window.scrollPadlock.setScrollPadlockStyle();
</script>

Usage

The library exports a setScrollPadlockStyle function which appends CSS styles addressing a default .scroll-padlock selector using the page default scrolling element and the window object to retrieve the values which would correspond to the following CSS variables:

These CSS variables can be used to implement the preferred approach to prevent the element scroll or to add the scrollbar gap componsation, see the following basic example:

.scroll-padlock {
  overflow: hidden;

  padding-right: var(--scrollbar-width);
}

Since each function call updates the CSS variables, a good time to call it is immediately before adding the CSS class that would lock the element scroll.

setScrollPadlockStyle();

document.scrollingElement.classList.add('scroll-padlock');

Options

The setScrollPadlockStyle function accepts an options object which customizes its behavior. Here are the available options:

setScrollPadlockStyle({
  element: document.querySelector('#custom-scrolling-element'),

  selector: '.custom-element-scroll-padlock',

  formatter: ({ clientWidth }) => `--width-without-scrollbar: ${clientWidth}px;`
});

Development

Node version 20.11.0 or higher is required in order to execute the tests.

npm test

To generate the unit tests coverage in a readable format, lcov can be used.

genhtml --branch-coverage lcov.info -o coverage

The locally built library is imported in the end-to-end tests, so a build is required.

npm run build

To run the end-to-end tests, use the following command:

npm run test:e2e