StickyState

repository·master·Indexed 20 days ago

https://github.com/soenkekluth/sticky-state

A high-performance, dependency-free JavaScript library (v2.4.1) that adds state detection to position:sticky elements and provides a polyfill for browsers without native support, including IE9+. It features an event API for sticky:on and sticky:off states, customizable class names for CSS integration, and a StickyStateCollection for managing multiple elements.

Tokens
1.8K
Snippets
9
Records
10
Agent score
22%

What's inside sticky-state

  1. Implement StickyState CSS

    master

    To ensure the polyfill and state classes work correctly, your CSS must include definitions for the base sticky class and the fallback fixed positioning. The is-sticky class is used to trigger the sticky state styles. If you customize className, stateClassName, fixedClass, or absoluteClass in the JavaScript options, ensure your CSS selectors match those values.

    .sticky {
      position: -webkit-sticky;
      position: sticky;
    }
    
    .sticky.sticky-fixed.is-sticky {
      position: fixed;
      -webkit-backface-visibility: hidden;
      -moz-backface-visibility: hidden;
      backface-visibility: hidden;
    }
    
    .sticky.sticky-fixed.is-sticky:not([style*="margin-top"]) {
      margin-top: 0 !important;
    }
    .sticky.sticky-fixed.is-sticky:not([style*="margin-bottom"]) {
      margin-bottom: 0 !important;
    }
    
    .sticky.sticky-fixed.is-absolute{
      position: absolute;
    }
  2. Configure StickyState options

    master

    When instantiating StickyState, you can pass an options object to customize class names, fallback behaviors, and scroll direction detection.

    Key options include:

    • disabled: Boolean to enable/disable the feature initially.
    • className: The base class for sticky elements (must match your CSS).
    • stateClassName: The class applied when the element is in its sticky state.
    • fixedClass: The fallback class used to implement position:fixed for polyfilling.
    • wrapperClass: The class for the placeholder element used during polyfilling.
    • wrapFixedSticky: If true, the sticky element is wrapped by the placeholder; if false, the placeholder is inserted right before it.
    • absoluteClass: Class used for position:absolute requirements in polyfilling.
    • scrollClass: An object to handle scroll direction classes (down, up, none) and a persist boolean.
    var StickyState = require('sticky-state');
    
    var stickyOptions = {
      disabled: false,
      className: 'sticky',
      stateClassName: 'is-sticky',
      fixedClass: 'sticky-fixed',
      wrapperClass: 'sticky-wrap',
      wrapFixedSticky: true,
      absoluteClass: 'is-absolute',
      scrollClass: {
        down: null,
        up: null,
        none: null,
        persist: false
      }
    };
    
    var stickyElements = new StickyState(document.querySelectorAll('.sticky'), stickyOptions);
  3. Listen to sticky state events

    master

    StickyState provides an event API to react to elements entering or leaving the sticky state. You can use the .on() method to attach listeners for sticky:on and sticky:off events. The event object e contains the target element.

    var StickyState = require('sticky-state');
    new StickyState(document.querySelectorAll('.sticky'))
      .on('sticky:on', function(e){console.log('sticky:on', e.target);})
      .on('sticky:off', function(e){console.log('sticky:off' ,e.target);});
  4. Listen to sticky state changes

    master

    Since StickyState extends EventDispatcher, you can listen to events triggered when the element enters or leaves the sticky state. The element target is passed to the event dispatcher.

    Events:

    • sticky:on: Fired when the element becomes sticky.
    • sticky:off: Fired when the element is no longer sticky.
    const sticky = new StickyState(el);
    
    sticky.on('sticky:on', () => {
      console.log('Element is now sticky!');
    });
    
    sticky.on('sticky:off', () => {
      console.log('Element is no longer sticky.');
    });
  5. Initialize StickyState for an element

    master

    To manage sticky behavior and polyfill position: sticky for an element, instantiate StickyState with the target DOM element and an optional configuration object. If you pass a NodeList as the first argument, the library will automatically create a StickyStateCollection for all elements in the list (excluding the first one).

    import StickyState from './sticky-state.js';
    
    const el = document.querySelector('.my-sticky-element');
    const options = {
      className: 'my-sticky-class',
      stateClassName: 'is-active'
    };
    
    const sticky = new StickyState(el, options);
  6. Disable or enable sticky behavior

    master

    You can programmatically enable or disable the sticky logic for an instance using the disable(value) method. Passing true will stop all sticky calculations and class applications.

    const sticky = new StickyState(el);
    
    // Disable sticky behavior
    sticky.disable(true);
    
    // Re-enable sticky behavior
    sticky.disable(false);
  7. Get current sticky and absolute state

    master

    Use getStickyState() to retrieve the current calculated state of the element. This is useful for manual logic checks outside of event listeners.

    const state = sticky.getStickyState();
    // Returns: { sticky: boolean, absolute: boolean }
    
    if (state.sticky) {
      // Do something while sticky
    }