Skip to content
Events for `position: sticky`
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.babelrc
.gitignore
CHANGELOG.md
LICENSE
README.md
demo.css
demo.scss
index.html
package-lock.json
package.json
rollup.config.js
sticky-events.css
sticky-events.js

README.md

Sticky Events

Events for position: sticky, without the need for an onscroll listener.

Installation

npm install sticky-events

Browser support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
No IE / Edge 16+ 55+ 56+ Polyfill 43+

Options

Option Name Type Default Description
container Element or Document document The element that contains your sticky elements. Grabs all sticky elements on the page by default.
enabled boolean true Enable sticky events immediately.
stickySelector string .sticky-events The selector to use to find your sticky elements within container.

Events

The StickyEvents class has constants we can use to listen for events.

Event Name Description
StickyEvents.CHANGE Fired when an element becomes stuck or unstuck
StickyEvents.STUCK Fired only when an element becomes stuck
StickyEvents.UNSTUCK Fired only when an element becomes unstuck

How to use

View demo

Given the following HTML:

<div class="my-sticky-container">
    <div>
        <h2 class="custom-sticky-selector">Sticky Heading 1</h2>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
    <div>
        <h2 class="custom-sticky-selector">Sticky Heading 2</h2>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
    <div>
        <h2 class="custom-sticky-selector">Sticky Heading 3</h2>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
</div>

We could configure StickyEvents like this:

import StickyEvents from 'sticky-events';


// Create new StickyEvents instance

const stickyEvents = new StickyEvents({
  container: document.querySelector('.my-sticky-container'),
  enabled: false,
  stickySelector: '.custom-sticky-selector'
});


// Enable events

stickyEvents.enableEvents();


// Add event listeners

const { stickyElements } = stickyEvents;

stickyElements.forEach(sticky => {
  sticky.addEventListener(StickyEvents.CHANGE, (event) => {
    sticky.classList.toggle('bg-dark', event.detail.isSticky);
  });
});


// Disable events

stickyEvents.disableEvents();

Deprecated

The following have been deprecated as of v2.3, and will be removed in v3.0:

  • observeStickyEvents
  • unobserveStickyEvents
  • StickyEvent
  • sticky-events.css
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.