API Reference

This section details every configuration option, callback, state property, and instance method available in ScrollBooster.


Constructor Configuration

Instantiate the library by passing an options object to the constructor: new ScrollBooster(options).

Core Properties

Property Type Default Description Edge Cases / Notes
viewport Element null Required. The DOM Node acting as the fixed-size bounding box. Initialization will fail and throw a console error if this is missing or not a valid Element.
content Element viewport.children[0] The DOM Node inside the viewport that will be manipulated. If omitted, ScrollBooster strictly assumes the first immediate child of the viewport is the content container.
scrollMode String undefined Defines the automated DOM manipulation technique. Accepts 'transform' or 'native'. If undefined, you must handle rendering manually via the onUpdate callback.
direction String 'all' Restricts the physics calculations to a specific axis. Accepts 'horizontal', 'vertical', or 'all'. Useful for strict 1D carousels or standard vertical lists.

Physics & Feel

Property Type Default Description Edge Cases / Notes
friction Number 0.05 Deceleration factor. Determines how quickly kinetic scrolling stops after pointer release. A value of 1 means no glide (stops instantly). 0.01 means a very long glide.
bounce Boolean true Enables the elastic "rubber-band" effect when hitting the boundary of the viewport. If set to false, scrolling hits a hard wall.
bounceForce Number 0.1 The elasticity factor of the bounce effect. A higher number equals a faster, stiffer snap back.

Input Handling & Interactivity

Property Type Default Description Edge Cases / Notes
pointerMode String 'all' Restricts input devices. Accepts 'touch' (ignores mouse), 'mouse' (ignores touch), or 'all'.
textSelection Boolean false Enables text selection inside the viewport. When true, it runs DOM traversal on click to find text nodes. If a text node is clicked, drag is cancelled. Disable for better performance if no text exists.
inputsFocus Boolean true Automatically prevents dragging if the target is an input, textarea, button, select, or label.
emulateScroll Boolean false Translates mouse wheel and trackpad scroll events into kinetic physics. Crucial for desktop UX on un-scrollable canvases.
preventDefaultOnEmulateScroll String/Boolean false Calls event.preventDefault() on wheel events. Accepts 'horizontal', 'vertical', or 'all'. Highly recommended to set to 'horizontal' on carousels to prevent trackpad "back page" gestures from firing.
lockScrollOnDragDirection String/Boolean false Detects initial drag angle and locks scrolling to that axis. Accepts 'horizontal', 'vertical', or 'all'. Prevents diagonal jittering when a user intends to swipe purely left/right.
dragDirectionTolerance Number 40 The angle tolerance (in degrees) for drag direction detection. Used in conjunction with lockScrollOnDragDirection.
pointerDownPreventDefault Boolean true Calls preventDefault on the mousedown event. Prevents native browser ghost-image dragging when grabbing images or links.

Callbacks

All callbacks are optional. They are passed as part of the initial configuration object and receive the current State Object.

Callback Signature Description Common Use Case
onUpdate(state) Fires continuously on every requestAnimationFrame while the content is moving (dragging or gliding). Syncing the physics state with a WebGL camera, React State, or custom DOM manipulation.
shouldScroll(state, event) Fires on pointerdown. Return true to allow dragging, or false to block it. Disabling drag if the user targets a specific UI widget (e.g., a map pin) inside the viewport.
onClick(state, event, isTouch) Fires when a standard click event is registered in the viewport. Intercepting <a> tag clicks. You can check state.isDragging to determine if it was a drag or a genuine click.
onPointerDown(state, event, isTouch) Fires immediately when the mouse or finger touches the viewport. Adding a custom "grabbing" CSS class to the body.
onPointerMove(state, event, isTouch) Fires on hardware mousemove or touchmove. Tracking raw pointer coordinates alongside the physics.
onPointerUp(state, event, isTouch) Fires when the user releases the pointer. Triggering a server save event based on the new resting position.
onWheel(state, event) Fires on hardware wheel events (requires emulateScroll: true). Custom wheel speed scaling.

The state Object

The state object is generated internally and passed to callbacks (onUpdate, onClick, etc.). It contains read-only real-time metrics.

{
    // Boolean: True if physics are active (either user is actively holding/dragging, or content is gliding/bouncing)
    isMoving: false,

    // Boolean: True ONLY if the user is actively holding the pointer down and has moved past the 0px threshold
    isDragging: false,

    // Object: The current calculated floats for the content's position
    position: {
        x: 120.55,
        y: -45.21
    },

    // Object: The absolute pixel distance the pointer has moved since the initial `pointerdown` event
    dragOffset: {
        x: 15.0,
        y: 0.0
    },

    // Number: The angle of the drag in degrees (up: 180, left: -90, right: 90, down: 0)
    dragAngle: 90, 

    // Object: Collision detection. True if the content has hit the mathematical boundary of the viewport
    borderCollision: {
        left: false,
        right: false,
        top: true,
        bottom: false
    }
}

Instance Methods

After initializing (const sb = new ScrollBooster(...)), you can control the instance programmatically.

setPosition(position)

Instantly teleports the content to the specified coordinates. It zeroes out velocity, meaning any active kinetic gliding stops immediately.

  • Arguments: position Object { x: Number, y: Number }
  • Usage: Resetting a map to the origin (0, 0).
// Instantly jump to x: 500, y: 100
sb.setPosition({ x: 500, y: 100 });

scrollTo(position)

Smoothly animates the content from its current position to the specified coordinates using the physics engine.

  • Arguments: position Object { x: Number, y: Number }
  • Usage: Creating a "Scroll to Top" or "Focus on Marker" button.
// Smoothly glide to x: 0, y: 0
sb.scrollTo({ x: 0, y: 0 });

updateMetrics()

Recalculates the maximum scroll boundaries by measuring the offsetWidth/scrollHeight of the viewport and content.

  • Arguments: None
  • Usage: Mandatory to call if you inject new items into the DOM, lazy-load images, or resize the browser window, as these actions change the physical dimensions of the content.
// Called after new data is fetched and injected into the DOM
sb.updateMetrics();

updateOptions(options)

Allows you to mutate the configuration properties without destroying and recreating the instance. It merges the new options with the existing ones.

  • Arguments: options Object (Any valid constructor properties).
  • Usage: Toggling bounce physics on or off dynamically based on app state.
sb.updateOptions({
    friction: 0.1,
    emulateScroll: false
});

getState()

Synchronously requests the current state object. Useful if you need the exact coordinates outside of an onUpdate loop.

const currentState = sb.getState();
console.log(currentState.position.x);

destroy()

Purges the physics loop and removes all attached mousedown, touchstart, mousemove, wheel, and click event listeners from the DOM.

  • Arguments: None
  • Usage: Crucial for Single Page Applications (SPAs). You must call this when the component unmounts to prevent severe memory leaks and ghost event firing.
// Inside a React useEffect cleanup, or Vue beforeDestroy hook:
sb.destroy();