scroll-timeline-polyfill

repository·master·Indexed 22 days ago

https://github.com/flackr/scroll-timeline

A polyfill for the CSS Scroll-driven Animations specification, providing support for ScrollTimeline and ViewTimeline in browsers that do not yet natively support them. It enables both JavaScript-based animations via the Web Animations API and CSS-based animations using animation-timeline: scroll() or view(). The library includes CSSOM support via installCSSOM(), providing CSS unit factory functions and classes such as CSSUnitValue, CSSMathValue, and CSSNumericValue.

Tokens
2K
Snippets
8
Records
9
Agent score
78%

What's inside scroll-timeline-polyfill

  1. Install and use the Scroll-timeline Polyfill

    master

    The Scroll-timeline Polyfill provides support for ScrollTimeline and ViewTimeline as defined by the CSS Scroll-driven Animations specification. You can use it by importing the JavaScript module directly into your site or by including it via a <script> tag.

    Note on CSS Hosting: Ensure your CSS is hosted on the same domain as your website or included directly within a <style> tag. Loading stylesheets from other origins may cause the polyfill to fail due to browser security restrictions.

    <!-- Via Script Tag -->
    <script src="https://flackr.github.io/scroll-timeline/dist/scroll-timeline.js"></script>
    
    <!-- Via ES Module Import -->
    <script type="module">
      import 'https://flackr.github.io/scroll-timeline/dist/scroll-timeline.js';
    </script>
  2. Work with CSSMathValue and its subclasses

    master

    The polyfill provides several classes for representing mathematical expressions in CSS, inheriting from CSSMathValue. These are used to represent complex calculations.

    Subclasses:

    • CSSMathSum: Represents a calc() sum (e.g., calc(10px + 20px)).
    • CSSMathProduct: Represents a calc() product.
    • CSSMathNegate: Represents a negation (e.g., -10px).
    • CSSMathInvert: Represents an inversion.
    • CSSMathMax / CSSMathMin: Represents max() or min() functions.
    • CSSNumericValue: The base class for parsing and simplifying numeric values via CSSNumericValue.parse(value).

    Example:

    // Note: These are typically used internally by the polyfill's logic
    // but are available on the window object.
    const sum = new CSSMathSum([CSS.px(10), CSS.px(20)]);
    console.log(sum.toString()); // "calc(10px, 20px)"
  3. Install CSSOM support via installCSSOM()

    master

    To enable the polyfilled CSS Object Model (CSSOM) extensions, call installCSSOM(). This function initializes the CSS namespace on the window object, defines various unit-specific factory functions (e.g., CSS.px(), CSS.percent()), and attaches numeric value classes like CSSUnitValue, CSSMathValue, and CSSKeywordValue to the global window object. If the environment already has these defined or if the installation fails, it will throw an error.

    // Call this to initialize the polyfill
    installCSSOM();
  4. Initialize the Scroll-timeline polyfill

    master

    To use the polyfill, simply import the main entrypoint. The library automatically executes initPolyfillIncludingCSS(), which performs the following logic:

    1. Checks if the host browser natively supports Scroll Timelines via initCSSPolyfill().
    2. If the browser supports Scroll Timelines, the polyfill skips initialization and logs a debug message to the console.
    3. If the browser does not support it, it executes initPolyfill() to enable the polyfill functionality.

    Because the initialization is triggered upon import, you do not need to call any specific setup functions manually in your application code.

    import './path/to/scroll-timeline-polyfill/src/index.js';
  5. Animate elements using the ScrollTimeline API

    master

    You can use the ScrollTimeline constructor within the Web Animations API to create animations driven by a scroll container. You can specify the source (the scrollable element) and define the animation range using CSSUnitValue.

    import 'https://flackr.github.io/scroll-timeline/dist/scroll-timeline.js';
    
    document.getElementById('parallax').animate(
        { transform: ['translateY(0)', 'translateY(100px)']},
        {
          fill: 'both',
          timeline: new ScrollTimeline({
            source: document.documentElement,
          }),
          rangeStart: new CSSUnitValue(0, 'px'),
          rangeEnd: new CSSUnitValue(200, 'px'),
        }
    );
  6. Animate elements using CSS scroll-timeline and view-timeline

    master

    The polyfill enables support for CSS-based scroll-driven animations. You can define an animation-timeline using scroll() or view() and set the animation-range directly in your stylesheet.

    @keyframes parallax-effect {
      to { transform: translateY(100px) }
    }
    
    #parallax {
      animation: parallax-effect linear both;
      animation-timeline: scroll(block root);
      animation-range: 0px 200px;
    }
  7. Manually initialize the Scroll-timeline polyfill with initPolyfill()

    master

    If you are not using a simple <script> tag to load the polyfill, you can manually initialize it by calling initPolyfill().

    This function performs the following actions:

    1. Feature Detection: It checks if window.ViewTimeline is already defined. If the browser natively supports Scroll-timeline, the function returns true and does nothing.
    2. Global Attachment: It attaches ScrollTimeline and ViewTimeline to the window object.
    3. WAAPI Augmentation: It patches the Web Animations API (WAAPI) by attaching the polyfill's animate method, getAnimations method (on both Element.prototype and document), and the Animation constructor to the global scope.

    Note: If the polyfill cannot attach these properties to the global objects (e.g., due to security restrictions or existing non-configurable properties), it will throw an Error.

    import { initPolyfill } from './path/to/scroll-timeline-polyfill/src/init-polyfill.js';
    
    try {
      initPolyfill();
      console.log('Scroll-timeline polyfill initialized successfully.');
    } catch (e) {
      console.error('Failed to initialize polyfill:', e.message);
    }
  8. Use CSS unit factory functions

    master

    Once installCSSOM() is called, the CSS object provides factory functions for various CSS units. These functions return a CSSUnitValue instance. Supported units include:

    • Numbers/Percentages: number, percent
    • Length: em, ex, px, cm, mm, in, pt, pc, Q, vw, vh, vmin, vmax, rems, ch
    • Angle: deg, rad, grad, turn
    • Time: ms, s, Hz, kHz
    • Resolution: dppx, dpi, dpcm
    • Other: fr

    Example usage:

    const pxValue = CSS.px(10);
    const percentValue = CSS.percent(50);
    // Example of using unit factories
    const pxValue = CSS.px(10);
    console.log(pxValue.toString()); // "10px"
    
    const percentValue = CSS.percent(50);
    console.log(percentValue.toString()); // "50%"
  9. Work with CSSUnitValue

    master

    A CSSUnitValue represents a numeric value with a specific CSS unit.

    Properties and Methods:

    • value: The numeric value (getter/setter).
    • unit: The unit string (getter).
    • to(unit): Converts the value to a different unit.
    • toSum(...units): Converts the value to a sum of multiple units.
    • type(): Returns the CSS type associated with the unit.
    • toString(): Returns the string representation (e.g., "10px").

    Example:

    const val = CSS.px(100);
    console.log(val.value); // 100
    console.log(val.unit); // "px"