Stuck.js

Stuck.js

A sticky library that stacks multiple sticky elements on top of each other and keeps them aligned when the page scrolls horizontally. No dependencies — jQuery not required.

GitHub / npm

Installation

npm module:

npm i -S stuck-js import Stuck from 'stuck-js'

<script>:

Load it from a CDN:

<script src="https://unpkg.com/stuck-js/lib/index.js"></script>

Or download it from the GitHub releases and drop ./lib/index.js into your project:

<script src="./vendor/stuck.js"></script>

How to use

<style> header { height: 100px; z-index: 100; } .ad { width: 300px; height: 250px; } </style> <body> <header style="height: 100px; z-index: 100;"> <h1>This is my first website</h1> <!-- header contents --> </header> <div> <main> <!-- main contents --> </main> <div id="js-sidebar"> <aside class="js-sticky-ad ad ad--01"><!-- ad contents --></aside> <aside class="js-sticky-ad ad ad--02"><!-- ad contents --></aside> </div> </div> <script src="https://unpkg.com/stuck-js/lib/index.js"></script> <script> const Stuck = StuckJs.Stuck; const instances = new Stuck([ { selector: '#js-header', marginTop: 0 }, { selector: '.js-sticky-ad', wrapper: '#js-sidebar' }, ], { marginTop: 10 }); </script> </body>

Loaded as a UMD bundle, the library is exposed on the global scope as window.StuckJs, or simply StuckJs.

Or, with npm and ES modules or TypeScript:

import { Stuck } from 'stuck-js'; // or const StuckJs = require('stuck-js'); const instances = new Stuck([ { selector: '#js-header', marginTop: 0 }, { selector: '.js-sticky-ad', wrapper: '#js-sidebar' }, ], { marginTop: 10 });

Options

Options are passed when you create a Stuck instance:

new Stuck(settings, defaultOptions, sharedStacking);

The first argument, settings, is the only required one. It takes either a single object or an array of them:

{ selector: string, marginTop?: number, wrapper?: HTMLElement|string, observe?: boolean, }

You can pass elements directly instead of a selector:

{ element: HTMLElement | HTMLElement[] | NodeList, marginTop?: number, wrapper?: HTMLElement|string, observe?: boolean, }

marginTop Number 0

The gap left above the element once it sticks — measured from the bottom of the sticky above it, or from the top of the window when nothing is stacked above.

wrapper HTMLElement parentElement|document.body

The node that bounds the stacking behaviour. Stickies stack within their wrapper and stop once they reach its bottom edge, so they never escape the section they belong to. It has to be an ancestor of the element, since this is position: sticky's own containing block.

observe boolean true

By default each sticky watches itself with a ResizeObserver, so the ones stacked below it move as its height changes. Set observe: false to skip that when the element never resizes.

The full API — Stuck, Sticky, their methods and the DOM they produce — is documented in the README on GitHub.