Convert Figma logo to code with AI

ftlabs logoftscroller

FTScroller is a cross-browser Javascript/CSS library to allow touch, mouse or scrollwheel scrolling within specified elements, with pagination, snapping and bouncing support.

1,186
121
1,186
59

Top Related Projects

Accelerated panning and zooming for HTML and Canvas

12,874

Smooth scrolling for the web

Imitates iOS native scrolling in JavaScript.

18,524

Stand-alone parallax scrolling library for mobile (Android + iOS) and desktop. No jQuery. Just plain JavaScript (and some love).

The javascript library for magical scroll interactions.

Quick Overview

FTScroller is a lightweight JavaScript library for creating smooth, hardware-accelerated scrolling areas on mobile and desktop browsers. It provides a native-like scrolling experience with momentum and bounce effects, particularly useful for touch devices.

Pros

  • Smooth, hardware-accelerated scrolling performance
  • Cross-platform compatibility (mobile and desktop)
  • Customizable options for scrolling behavior
  • Lightweight and easy to integrate

Cons

  • Limited recent updates (last commit was in 2017)
  • May require additional polyfills for older browser support
  • Documentation could be more comprehensive
  • Potential conflicts with native scrolling on some devices

Code Examples

Creating a basic scroller:

var scroller = new FTScroller(document.getElementById('scrollable-element'), {
    scrollingX: true,
    scrollingY: true,
    bouncing: true
});

Adding event listeners:

scroller.addEventListener('scrollstart', function() {
    console.log('Scrolling started');
});

scroller.addEventListener('scrollend', function() {
    console.log('Scrolling ended');
});

Programmatically scrolling to a specific position:

scroller.scrollTo(0, 500, 300); // Scroll to x: 0, y: 500 over 300ms

Getting Started

  1. Include the FTScroller script in your HTML:
<script src="path/to/ftscroller.js"></script>
  1. Create a container element in your HTML:
<div id="scroller-container">
    <div id="scroller-content">
        <!-- Your scrollable content here -->
    </div>
</div>
  1. Initialize the scroller in your JavaScript:
document.addEventListener('DOMContentLoaded', function() {
    var scroller = new FTScroller(document.getElementById('scroller-container'), {
        scrollingX: false,
        scrollingY: true,
        bouncing: true
    });
});
  1. Style your container and content elements as needed:
#scroller-container {
    width: 300px;
    height: 400px;
    overflow: hidden;
}

#scroller-content {
    width: 100%;
}

Competitor Comparisons

Accelerated panning and zooming for HTML and Canvas

Pros of scroller

  • More comprehensive documentation and examples
  • Supports both horizontal and vertical scrolling
  • Offers advanced features like snapping and momentum

Cons of scroller

  • Larger file size and potentially higher performance overhead
  • Less frequently updated (last update in 2013)
  • More complex API, which may be overkill for simple use cases

Code Comparison

ftscroller:

var scroller = new FTScroller(element, {
    scrollingX: true,
    scrollingY: true,
    bouncing: true
});

scroller:

var scroller = new Scroller(function(left, top, zoom) {
    // render logic
}, {
    scrollingX: true,
    scrollingY: true,
    bouncing: true
});

Key Differences

  • ftscroller is more lightweight and focused on touch-based scrolling
  • scroller offers more advanced features and customization options
  • ftscroller has a simpler API, making it easier to implement for basic use cases
  • scroller provides better support for desktop environments and complex scrolling behaviors

Use Cases

  • ftscroller: Ideal for simple, touch-based scrolling in mobile web applications
  • scroller: Better suited for complex scrolling scenarios, cross-platform applications, or projects requiring advanced customization

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project, such as performance needs, target platforms, and desired scrolling behaviors.

12,874

Smooth scrolling for the web

Pros of iScroll

  • More comprehensive feature set, including zoom, snap, and infinite scrolling
  • Wider browser compatibility, including older versions of IE
  • Larger community and more frequent updates

Cons of iScroll

  • Larger file size and potentially higher performance overhead
  • More complex configuration and setup process
  • May introduce scrolling behavior inconsistencies across different devices

Code Comparison

iScroll initialization:

var myScroll = new IScroll('#wrapper', {
    scrollX: true,
    scrollY: true,
    mouseWheel: true,
    wheelAction: 'zoom'
});

FTScroller initialization:

var scroller = new FTScroller(document.getElementById('wrapper'), {
    scrollingX: true,
    scrollingY: true,
    bouncing: false
});

Both libraries offer similar basic functionality for creating custom scrollable areas. iScroll provides more options out of the box, while FTScroller focuses on simplicity and performance. iScroll's initialization allows for more customization, including zoom functionality, while FTScroller's setup is more straightforward.

The choice between the two depends on project requirements, target browsers, and desired features. iScroll is better suited for complex scrolling needs and broader compatibility, while FTScroller may be preferable for simpler use cases and performance-critical applications.

Imitates iOS native scrolling in JavaScript.

Pros of scrollability

  • Lightweight and simple implementation
  • Supports both vertical and horizontal scrolling
  • Easy to integrate into existing projects

Cons of scrollability

  • Less actively maintained (last update in 2012)
  • Limited documentation and examples
  • Fewer customization options compared to ftscroller

Code Comparison

scrollability:

scrollability.init();
scrollability.enable(element);

ftscroller:

var scroller = new FTScroller(element, {
    scrollingX: true,
    scrollingY: true,
    bouncing: false
});

Key Differences

  • ftscroller offers more advanced features like momentum scrolling and bounce effects
  • scrollability focuses on simplicity and ease of use
  • ftscroller has better cross-browser compatibility and mobile support
  • scrollability is more suitable for basic scrolling needs, while ftscroller is better for complex implementations

Use Cases

  • Choose scrollability for quick implementation in simple projects
  • Opt for ftscroller when building feature-rich applications with advanced scrolling requirements

Community and Support

  • ftscroller has more recent updates and active community support
  • scrollability may require more effort to adapt to modern web standards

Performance

  • Both libraries offer good performance, but ftscroller may have an edge in handling complex scrolling scenarios
  • scrollability's simplicity can lead to better performance in basic use cases
18,524

Stand-alone parallax scrolling library for mobile (Android + iOS) and desktop. No jQuery. Just plain JavaScript (and some love).

Pros of skrollr

  • More versatile, supporting various scrolling effects and animations
  • Extensive documentation and community support
  • No dependencies, lightweight and easy to implement

Cons of skrollr

  • Steeper learning curve due to its advanced features
  • May be overkill for simple scrolling needs
  • Less optimized for mobile devices compared to ftscroller

Code Comparison

skrollr:

var s = skrollr.init();

<div data-0="background-color:rgb(0,0,255);" data-500="background-color:rgb(255,0,0);">
    This element will gradually change from blue to red between 0-500px
</div>

ftscroller:

var scroller = new FTScroller(document.getElementById('scrollable'), {
    scrollingX: false,
    scrollbars: true,
    updateOnChanges: true
});

Key Differences

  • skrollr focuses on scroll-based animations and effects
  • ftscroller is primarily for touch-friendly scrolling containers
  • skrollr uses data attributes for defining animations
  • ftscroller uses a more traditional JavaScript API
  • skrollr has a larger feature set but may be more complex to use

Both libraries serve different purposes: skrollr for creative scroll-based animations, and ftscroller for optimized touch scrolling. Choose based on your project's specific needs and target devices.

The javascript library for magical scroll interactions.

Pros of ScrollMagic

  • More feature-rich, offering complex animations and scene-based scrolling effects
  • Active development and larger community support
  • Extensive documentation and examples available

Cons of ScrollMagic

  • Steeper learning curve due to more complex API
  • Larger file size, which may impact page load times
  • Requires additional libraries for advanced animations (e.g., GSAP)

Code Comparison

ScrollMagic:

var controller = new ScrollMagic.Controller();
var scene = new ScrollMagic.Scene({
    triggerElement: "#trigger",
    duration: 300
})
.setTween("#animate", {scale: 2})
.addTo(controller);

FTScroller:

var scroller = new FTScroller(document.getElementById('wrapper'), {
    scrollingX: false,
    scrollbars: true,
    updateOnChanges: true
});

ScrollMagic offers more complex scene-based animations tied to scroll events, while FTScroller focuses on basic touch-friendly scrolling functionality. ScrollMagic provides greater flexibility for creating interactive scroll-based experiences, but FTScroller is simpler to implement for basic scrolling needs. The choice between the two depends on the specific requirements of your project, with ScrollMagic being better suited for advanced animations and FTScroller for straightforward scrolling implementations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

FTScroller

FTScroller is a library for adding momentum scrolling to web content on devices with a touch interface, compatible across most modern platforms including desktop browsers. Although recently support for overflow: scroll (or touch equivalents) has increased, this is often still not implemented in a cross-platform or backwards-compatible way, and with no support for features like snapping.

FTScroller is developed by FT Labs, part of the Financial Times. It is inspired by Touchscroll and Zynga Scroller, but is a complete rewrite. It is extensively used in the FT Web App, and was developed to achieve better performance and compatibility, including mouse and touch input.

Usage

Include ftscroller.js in your JavaScript bundle or add it to your HTML page like this:

<script type='text/javascript' src='/path/to/ftscroller.js'></script>

The script must be loaded prior to instantiating a scroller on any element of the page.

To create a scroller, with a few minimal options:

var containerElement, scroller;

containerElement = document.getElementById('scrollcontainer');

scroller = new FTScroller(containerElement, {
	scrollbars: false,
	scrollingX: false
});

Examples

FTScroller is designed to accommodate a range of use cases. Here are some examples - feel free to copy the code and use as the basis for your own projects.

Options

Options must be specified at create-time by passing a JSON object as the second argument to the FTScroller constructor.

  • alwaysScroll Whether to always enable scrolling, even if the content of the scroller is not large enough to spill out of the container. This makes the scroller behave more like an element set to "overflow: scroll", with bouncing always occurring if enabled (boolean, default false)
  • baseAlignments Determines where to anchor the content when the scroller is set up, specified individually for each axis using a JSON object with the keys x and y. Valid alignments for each axis are -1 (top or left), 0 (center), and 1 (bottom or right). For example, the default baseAlignments of {x:-1,y:-1} will display the scroller initially scrolled to the top left of its range. This also affects the alignment of content where the content is smaller than the scroller.
  • bouncing Allow scroll bouncing and elasticity near the ends of the range and at snap points (boolean, default true)
  • contentWidth Define the scrollable width; if not defined, this will match the content width (numeric, default undefined)
  • contentHeight Define the scrollable height; if not defined, this will match the content height (numeric, default undefined)
  • disabledInputMethods Define any input methods to disable; on some multi-input devices custom behaviour may be desired for some scrollers. No inputs methods are disabled by default. (object, default { mouse: false, touch: false, scroll: false, pointer: false, focus: false })
  • enableRequestAnimationFrameSupport FTScroller will use requestAnimationFrame on platforms which support it, which is highly recommended; however this can result in the animation being a further half-frame behind the input method, increasing perceived lag slightly. To disable this, set this property to false. (boolean, default true)
  • flinging Allow a fast scroll to continue with momentum when released (boolean, default true)
  • hwAccelerationClass FTScroller uses normal translate properties rather than translate3d to position content when scrolling, and triggers hardware acceleration by adding CSS properties (specifically backface-visibility) to this class on platforms that support it. Adjusting this class allows for negotiating complex CSS inheritance to override the default behaviour of FTScroller if you want to change or disable backing layers/3D acceleration. (string, default an internal class which triggers backing layers)
  • maxFlingDuration Set the maximum time (ms) that a fling can take to complete once the input has ended (numeric, default 1000ms)
  • scrollbars Whether to display iOS-style scrollbars (which you can style yourself using .ftscroller_scrollbar and .ftscroller_scrollbarx/.ftscroller_scrollbary) while the content is animating (boolean, default true)
  • scrollBoundary The initial movement required to trigger a full scroll, in pixels; this is the point at which the scroll is exclusive to this particular FTScroller instance and flings become active (integer, default 1)
  • scrollingClassName The classname to add to the scroller container when it is being actively scrolled. This is disabled by default as it can cause a CSS relayout if enabled, but allows custom styling in response to scrolls (string, default not set)
  • scrollResponseBoundary The initial movement required to trigger a visual scroll update, in pixels (integer, default 1)
  • scrollingX Enable scrolling on the X axis if content is available (boolean, default true)
  • scrollingY Enable scrolling on the Y axis if content is available (boolean, default true)
  • singlePageScrolls (was paginatedSnap) If snapping is enabled, restricts each scroll movement to one 'page' span. That is, if set to true, it will not be possible to move more than one page in a single movement. (boolean, default false)
  • snapping Enable snapping of content to defined 'pages' or segments (boolean, default false)
  • snapSizeX Define the horizontal interval content should snap to, in pixels. If this is not set, snapping will be based on pages corresponding to the container size. (numeric, default undefined)
  • snapSizeY Define the vertical interval content should snap to, in pixels. If this is not set, snapping will be based on pages corresponding to the container size. (numeric, default undefined)
  • updateOnChanges Automatically detect changes to the content of the scrollable element and update the scroller dimensions whenever the content changes. This is set to false automatically if contentWidth and contentHeight are specified (boolean, default true)
  • updateOnWindowResize Automatically catch changes to the window size and update the dimensions of the scroller. It's advisable to set this to true if the scroller has a flexible width or height based on the viewport size. (boolean, default false)
  • windowScrollingActiveFlag Whether to use a global property of the window object to control whether to allow scrolling to start or not. If the specified window property is set to a truthy value, the scroller will not react to input. If the property is not truthy, the scroller will set it to itself and will scroll. Where multiple scrollers exist on the same page, this ensures that only one can be used at a time, which is particularly useful for nested scrollers (see Multiple vertical scrollers in a horizontally paged scroller). Note that FTScroller automatically allows only one scroller instance to be scrolled at once; use this flag to coordinate input with other parts of your code. (string, default not set)
  • flingBezier The bezier curve to use for momentum-like flings. (CubicBezier, default CubicBezier(0.103, 0.389, 0.307, 0.966))
  • bounceDecelerationBezier The bezier curve to use for deceleration when a fling hits the bounds. (CubicBezier, default CubicBezier(0, 0.5, 0.5, 1))
  • bounceBezier The bezier curve to use for bouncebacks when the scroll exceeds the bounds. (CubicBezier, default CubicBezier(0.7, 0, 0.9, 0.6))
  • invertScrollWheel If the scroller is constrained to an x axis, convert y scroll to allow single-axis scroll wheels to scroll constrained content. (boolean, default true)

Public interface

Once the scroller has been applied to an element, the return value from the constructor is an object that offers a number of public properties, methods and events.

Properties

  • scrollHeight Gets the scrollable height of the contained content. Read only
  • scrollLeft Gets or sets the current left scroll offset of the scroller in pixels. When set, will cause the scroller to jump to that position (without animating)
  • scrollTop Gets or sets the current top scroll offset of the scroller in pixels. When set, will cause the scroller to jump to that position (without animating)
  • scrollWidth Gets the scrollable width of the contained content. Read only
  • segmentCount When snapping is enabled, returns the number of snap segments (which in many use cases can be considered 'pages'). Read only.
  • currentSegment Returns the index of the current segment, starting from 0. Updated when the scroller comes to rest on a new segment. Applies only when snapping is set to true. Read only.
  • contentContainerNode Returns the DOM node that contains the scroller contents, for use if you want to amend the contents. Read only.

Methods

  • addEventListener(eventname, callback) Attaches a specified function to an FTScroller custom event. Available events are listed in the events section below. The function will be called by FTScroller when the event occurs.
  • destroy(removeElements) Unbinds all event listeners to prevent circular references preventing items from being deallocated, and clean up references to dom elements. Does not remove scroller markup from the DOM unless the optional removeElements argument is set to a truthy value.
  • removeEventListener(eventname, callback) Removes a previously bound function from an event. The function specified in the mathod must be the same object reference passed in the addEventListener call (not a redefinition of the same function code)
  • scrollBy(horizontal, vertical[, duration]) Similar to scrollTo but allows scrolling relative to the current position rather than to an absolute offset.
  • scrollTo(left, top[, duration]) Scroll to a specified left and top offet over a specified duration. If duration is zero, no animation will occur. If duration is true FTScroller will itself choose a duration based on the distance to be scrolled. The left and top inputs will be constrained by the size of the content and the snap points. If false is supplied for either left or top, that axis will not be scrolled and will retain its current offset.
  • setSnapSize(width, height) Configures the snapping boundaries within the scrolling element if snapping is active. If this is never called, segment size defaults to the width and height of the scroller, ie. page-at-a-time.
  • updateDimensions(width, height[, nosnap]) Sets the dimensions of the scrollable content. If snapping is enabled, and you wish to disable updates of the snapping grid and prevent the current position from being updated, set nosnap to true; it defaults to false if not supplied.
  • setDisabledInputMethods(disabledInputMethods) Set the input methods to disable. No inputs methods are disabled by default. (object, default { mouse: false, touch: false, scroll: false, pointer: false, focus: false })

Prototype methods

  • getPrependedHTML([excludeXAxis, excludeYAxis, hwAccelerationClass]) - Provides half of the HTML that is used to construct the scroller DOM, for use to save a DOM manipulation on Scroller initialisation (see Tips and tricks below). Optionally the x and y axes can be excluded, or a custom layer backing triggering class can be supplied (see the hwAccelerationClass option for the constructor).
  • getAppendedHTML([excludeXAxis, excludeYAxis, hwAccelerationClass, scrollbars]) - Provides the second half of the HTML that is used to construct the scroller DOM, for use to save a DOM manipulation on Scroller initialisation (see Tips and tricks below). Optionally the x and y axes can be excluded, or a custom layer backing triggering class can be supplied (see the hwAccelerationClass option for the constructor). Pass a truthy value in for the scrollbars parameter if you are enabling scrolling. Any parameters should match those passed in to getPrependedHTML.

Events

Events can be bound with the addEventListener method. Events are fired syncronously. Regardless of the event, the listener function will receive a single argument.

  • scroll Fired whenever the scroll position changes, continuously if an input type is modifying the position. Passes an object containing scrollLeft and scrollTop properties matching the new scroll position, eg {scrollLeft:10, scrollTop:45}
  • scrollstart Fired when a scroll movement starts. Passes an object with the same characteristics as scroll.
  • scrollend Fired when a scroll movement ends. Passes an object with the same characteristics as scroll.
  • segmentdidchange Fires on completion of a scroll movement, if the scroller is on a different segment to the one it was on at the start of the movement. Passes an object with segmentX and segmentY properties.
  • segmentwillchange Fires as soon as the scroll position crosses a segment boundary, during a scroll movement. Passes an object with segmentX and segmentY properties.
  • reachedstart Fires when the scroll position reaches the top or left of a scroller. Passes an object with an axis property indicating whether the x or y axis reached its start position.
  • reachedend Fires when the scroll position reaches the bottom or right of a scroller. Passes an object with an axis property indicating whether the x or y axis reached its end position.

Compatibility

FTScroller supports input via mouse or touch on the following browsers:

  • Apple Mobile Safari (iOS 3.2+ confirmed, best after 4.0+)
  • Google Android Browser (Android 2.2+ confirmed)
  • Microsoft Internet Explorer 10 (Windows 8 RTM confirmed)
  • RIM BlackBerry PlayBook (2.0 confirmed, 1.0 should be fine)
  • Most modern desktop browsers (IE 9+, FF 4+, Safari 3+, Chrome 1+, Opera 11.5+ - ECMAScript 5 getters and setters are currently used)

Tips and tricks

  • If you are putting together the DOM in JavaScript using HTML or a template, it's advantageous to use the prototype methods for getPrependedHTML and getAppendedHTML to add the FTScroller HTML at the same time. If the elements are added to the very start and very end of the content within the element passed in to the constructor (ignoring whitespace), the Scroller instantiation will detect this and skip the DOM manipulation step, leading to faster instantiation without an additional layout.
  • If scrolling is going to only occur along one axis, setting scrollingX or scrollingY to false as part of the construction options skips creating of the corresponding DOM element, saving memory (particularly when using hardware acceleration).
  • Depending on your CSS, you may find that you can't scroll quite to the bottom of your content. This is typically a collapsing margin issue — the contents are measured, then wrapped in additional elements, but the margins spilling out of the contents can't be measured. If you see this, an easy fix is typically to put overflow: hidden either your scrollable element or its contents; that will act as a boundary for margins so everything can be measured, and typically has no effect on appearance when applied to the content as the scrollable content won't have dimensional limits.

Credits and collaboration

The lead developer of FTScroller is Rowan Beentje at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. Enjoy.