ScrollBooster

repository·master·Indexed 21 days ago

https://github.com/ilyashubin/scrollbooster

A lightweight (~2KB gzipped) drag-to-scroll micro library that enables smooth content scrolling via mouse/touch dragging, trackpads, or mouse wheels. It supports both 'transform' and 'native' scroll modes, elastic bounce effects, and provides a comprehensive API for controlling scroll position and state.

Tokens
2.9K
Snippets
7
Records
11
Agent score
27%

What's inside scrollbooster

  1. Basic Usage of ScrollBooster

    master

    To initialize ScrollBooster, create a new instance of the ScrollBooster class and provide a configuration object. At minimum, you must specify the viewport element. It is recommended to set scrollMode to 'transform' for smooth CSS-based scrolling.

    import ScrollBooster from 'scrollbooster';
    
    new ScrollBooster({
        viewport: document.querySelector('.viewport'),
        scrollMode: 'transform'
    });
  2. Configure ScrollBooster options

    master

    The ScrollBooster constructor accepts an options object to customize scrolling behavior.

    OptionTypeDefaultDescription
    viewportDOM NodenullContent viewport element (required)
    contentDOM Nodeviewport childScrollable content element inside viewport
    scrollModeStringundefinedScroll technique: 'transform' or 'native'
    directionString'all'Scroll direction: 'horizontal', 'vertical', or 'all'
    bounceBooleantrueEnables elastic bounce effect at borders
    textSelectionBooleanfalseEnables text selection inside viewport
    inputsFocusBooleantrueEnables focus for input, textarea, button, select, and label
    pointerModeString'all''touch' (touch only), 'mouse' (desktop only), or 'all'
    frictionNumber0.05How fast scrolling stops after pointer release
    bounceForceNumber0.1Elastic bounce effect factor
    emulateScrollBooleanfalseEnables mouse wheel/trackpad emulation
    preventDefaultOnEmulateScrollStringfalsePrevents default scroll when emulateScroll is enabled. Values: 'horizontal' or 'vertical'
    lockScrollOnDragDirectionStringfalseDetects direction and locks/prevents default events. Values: 'horizontal', 'vertical', or 'all'
    dragDirectionToleranceNumber40Tolerance for horizontal/vertical drag detection
    onUpdateFunctionnoopHandler for scrolling state (receives state object)
    onClickFunctionnoopClick handler (receives state, event, and isTouchDevice)
    onPointerDownFunctionnoopmousedown/touchstart handler
    onPointerUpFunctionnoopmouseup/touchend handler
    onPointerMoveFunctionnoopmousemove/touchmove handler
    onWheelFunctionnoopwheel event handler
    shouldScrollFunctionnoopFunction to permit/disable scrolling. Receives state and event object. Returns true or false
  3. Initialize ScrollBooster

    master

    To use ScrollBooster, instantiate the ScrollBooster class by passing an options object. At a minimum, you must provide a viewport (the container element) and a content (the scrollable element). If content is not provided, it defaults to the first child of the viewport.

    Common configuration options include:

    • direction: 'all', 'vertical', or 'horizontal'.
    • pointerMode: 'all', 'touch', or 'mouse'.
    • scrollMode: 'transform' (uses CSS transforms) or 'native' (uses native scroll).
    • bounce: Boolean to enable/disable the bounce effect at edges.
    • friction: Number to control scroll friction.
    • textSelection: Boolean to enable/disable text selection during interaction.
    • inputsFocus: Boolean to enable/disable focus on input elements.
    • emulateScroll: Boolean to enable mousewheel emulation.
    • onUpdate: Callback function triggered on every state change.
    import ScrollBooster from 'scrollbooster';
    
    const sb = new ScrollBooster({
      viewport: document.querySelector('.viewport'),
      content: document.querySelector('.content'),
      direction: 'all',
      onUpdate: (state) => {
        // Handle state updates
      }
    });
  4. Full ScrollBooster implementation example

    master

    This example demonstrates how to use onUpdate for manual transform-based scrolling, shouldScroll to prevent scrolling on specific elements (like buttons), and onClick to prevent default link behavior.

    const viewport = document.querySelector('.viewport');
    const content = document.querySelector('.scrollable-content');
    
    const sb = new ScrollBooster({
      viewport,
      content,
      bounce: true,
      textSelection: false,
      emulateScroll: true,
      onUpdate: (state) => {
        // state contains useful metrics: position, dragOffset, dragAngle, isDragging, isMoving, borderCollision
        // you can control scroll rendering manually without 'scrollMethod' option:
        content.style.transform = `translate(
          ${-state.position.x}px,
          ${-state.position.y}px
        )`;
      },
      shouldScroll: (state, event) => {
        // disable scroll if clicked on button
        const isButton = event.target.nodeName.toLowerCase() === 'button';
        return !isButton;
      },
      onClick: (state, event, isTouchDevice) => {
        // prevent default link event
        const isLink = event.target.nodeName.toLowerCase() === 'link';
        if (isLink) {
          event.preventDefault();
        }
      }
    });
    
    // methods usage examples:
    sb.updateMetrics();
    sb.scrollTo({ x: 100, y: 100 });
    sb.updateOptions({ emulateScroll: false });
    sb.destroy();
  5. Use ScrollBooster methods

    master

    The ScrollBooster instance provides several methods to control the scrolling state and instance lifecycle:

    • setPosition({ x, y }): Sets a new scroll position in the viewport.
    • scrollTo({ x, y }): Smoothly scrolls to a position in the viewport.
    • updateMetrics(): Forces recalculation of element metrics (use when content size changes dynamically).
    • updateOptions(options): Updates configuration using any property from the Options object.
    • getState(): Returns the current scroll state (same format as onUpdate).
    • destroy(): Removes all event listeners and cleans up the instance.
  6. Smoothly scroll to a target position

    master

    Use the scrollTo method to animate the scroll position to a specific coordinate. This uses an internal force-based animation loop for a smooth effect.

    // Scroll to x: 100, y: 200
    sb.scrollTo({ x: 100, y: 200 });
    sb.scrollTo({ x: 100, y: 200 });
  7. Get the current ScrollBooster state

    master

    Call getState() to retrieve the current interaction and position metrics. The returned object contains:

    • isMoving: boolean - True if the content is currently scrolling or being dragged.
    • isDragging: boolean - True if a pointer drag is in progress.
    • position: { x: number, y: number } - The current scroll position (relative to the top-left).
    • dragOffset: { x: number, y: number } - The current drag offset.
    • dragAngle: number - The angle of the current drag (up: 180, left: -90, right: 90, down: 0).
    • borderCollision: { left: boolean, right: boolean, top: boolean, bottom: boolean } - Whether the content is colliding with the viewport edges.
    const state = sb.getState();
    console.log(state.position);
    console.log(state.isMoving);
  8. ScrollBooster Methods

    master

    The ScrollBooster instance provides the following methods to control scrolling and state:

    • updateOptions(options): Merges new options into the existing configuration and triggers an update.
    • scrollTo(position): Smoothly scrolls to the specified { x, y } coordinates.
    • setPosition(position): Manually sets the scroll position to { x, y } without velocity.
    • getState(): Returns the current state of the instance.
    • destroy(): Removes all DOM event listeners and cleans up the instance.
  9. ScrollBooster Configuration Options

    master

    The ScrollBooster constructor accepts an options object with the following properties:

    PropertyTypeDefaultDescription
    viewportElementRequiredThe container element.
    contentElementviewport.children[0]The scrollable content element.
    directionString'all'Scroll direction: 'all', 'vertical', or 'horizontal'.
    pointerModeString'all'Support mode: 'all', 'touch', or 'mouse'.
    scrollModeStringundefinedScrolling technique: 'transform' or 'native'.
    bounceBooleantrueEnables bounce effect at edges.
    bounceForceNumber0.1Bounce effect factor.
    frictionNumber0.05Scroll friction factor.
    textSelectionBooleanfalseEnables text selection.
    inputsFocusBooleantrueEnables focus on input elements.
    emulateScrollBooleanfalseEnables mousewheel emulation.
    preventDefaultOnEmulateScrollStringfalseDirection to prevent default on emulate scroll: 'vertical', 'horizontal'.
    preventPointerMoveDefaultBooleantruePrevents default pointer move behavior.
    lockScrollOnDragDirectionStringfalseLock scroll to direction: 'vertical', 'horizontal', or 'all'.
    pointerDownPreventDefaultBooleantruePrevents default on pointer down.
    dragDirectionToleranceNumber40Tolerance for determining drag direction.
    onPointerDownFunction() => {}Callback: (state, event, isTouch) => {}
    onPointerUpFunction() => {}Callback: (state, event, isTouch) => {}
    onPointerMoveFunction() => {}Callback: (state, event, isTouch) => {}
    onClickFunction() => {}Callback: (state, event, isTouch) => {}
    onUpdateFunction() => {}Callback: (state) => {}
    onWheelFunction() => {}Callback: (state, event) => {}
    shouldScrollFunction() => truePredicate: (state, event) => boolean to allow/disable scroll.