scroll-lock-body

scroll lock the body and remember the position

Usage no npm install needed!

<script type="module">
  import scrollLockBody from 'https://cdn.skypack.dev/scroll-lock-body';
</script>

README

scroll-lock-body

License Library minified size Library minified + gzipped size

About

Minimal JS library which supports scroll lock on the body and remembers the scroll position.
This version uses margin-top approach to remember the scroll-position.

Alternate version with simpler implementation

An alternate version with same API exists where there are no required CSS
https://github.com/kunukn/scroll-lock-body-2

CSS required

:warning: ️You need to add style (transition) in your own stylesheet to add animation. Here is an example.

<style>
  html {
    overflow-y: scroll;
  }
  html[data-scroll-lock-is-active] > body {
    overflow: hidden;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    position: fixed;
  }
  body {
    margin: 0;
    overflow-y: auto; /* overflow-y: scroll -> shows double scroll */
  }
</style>

Demo

Codepen VanillaJS View Edit
Codesandbox VanillaJS View Edit
Codesandbox VueJS View Edit

Installation

This library is published in the NPM registry and can be installed using any compatible package manager.

npm install scroll-lock-body --save

# For Yarn, use the command below.
yarn add scroll-lock-body

Usage

import {
  enableScrollLock,
  disableScrollLock,
  isScrollLockEnabled,
} from 'scroll-lock-body';

// Run this to lock the body scroll
enableScrollLock();

// Run this to unlock the body scroll
disableScrollLock();

// Run this to get the lock state
isScrollLockEnabled(); // returns true or false

Installation from CDN

This module has an UMD bundle available through JSDelivr and Unpkg CDNs.

<!-- For UNPKG use the code below. -->
<script src="https://unpkg.com/scroll-lock-body"></script>

<!-- For JSDelivr use the code below. -->
<script src="https://cdn.jsdelivr.net/npm/scroll-lock-body"></script>

<script>
  // UMD module is exposed through the "scrollLockBody" global variable.
  console.log(scrollLockBody);
</script>

Explore the dist files

https://unpkg.com/scroll-lock-body/

Documentation

Documentation generated from source files by Typedoc.

:warning: ️avoid having direct children in body which has position sticky. e.g.

<style>
  body > .some-element {
    position: sticky; /* use position fixed or absolute instead */
  }
</style>

License

Released under MIT License.