Convert Figma logo to code with AI

russellsamora logoscrollama

Scrollytelling with IntersectionObserver.

5,772
276
5,772
11

Top Related Projects

Animate elements as they scroll into view.

The javascript library for magical scroll interactions.

26,486

Animate on scroll library

3,593

🚀 Performance focused, lightweight scroll animation library 🚀

🛤 Detection of elements in viewport & smooth scrolling with parallax.

Quick Overview

Scrollama is a modern, lightweight JavaScript library for creating scroll-driven interactions. It simplifies the process of building scroll-based storytelling, data visualizations, and interactive content by providing an easy-to-use API for detecting scroll progress and triggering events.

Pros

  • Simple and intuitive API for scroll-based interactions
  • Lightweight and dependency-free
  • Supports both mobile and desktop browsers
  • Flexible and customizable for various scroll-driven scenarios

Cons

  • Limited built-in animation capabilities (relies on external libraries for complex animations)
  • May require additional setup for more complex scroll-based interactions
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Basic step setup:
const scroller = scrollama();

scroller
  .setup({
    step: '.step'
  })
  .onStepEnter(response => {
    console.log(`Entered step ${response.index}`);
  })
  .onStepExit(response => {
    console.log(`Exited step ${response.index}`);
  });
  1. Triggering animations based on scroll progress:
scroller
  .setup({
    step: '.step',
    progress: true
  })
  .onStepProgress(response => {
    const { progress } = response;
    // Animate based on progress (0 to 1)
    element.style.opacity = progress;
  });
  1. Using offset to control when steps trigger:
scroller
  .setup({
    step: '.step',
    offset: 0.5 // Trigger when step is 50% in view
  })
  .onStepEnter(response => {
    // Trigger animation or update content
    updateContent(response.index);
  });

Getting Started

  1. Install Scrollama:
npm install scrollama
  1. Import and initialize in your JavaScript file:
import scrollama from 'scrollama';

const scroller = scrollama();

scroller
  .setup({
    step: '.step-class'
  })
  .onStepEnter(response => {
    // Handle step enter
  })
  .onStepExit(response => {
    // Handle step exit
  });
  1. Add step elements to your HTML:
<div class="step-class">Step 1</div>
<div class="step-class">Step 2</div>
<div class="step-class">Step 3</div>

Competitor Comparisons

Animate elements as they scroll into view.

Pros of ScrollReveal

  • More versatile, can animate any element, not just for scrollytelling
  • Easier to set up and use for simple reveal animations
  • Supports more browsers, including older versions

Cons of ScrollReveal

  • Less suitable for complex scrollytelling narratives
  • Doesn't provide built-in progress tracking or step-based animations
  • May require more custom JavaScript for advanced scroll-based interactions

Code Comparison

ScrollReveal:

ScrollReveal().reveal('.headline');
ScrollReveal().reveal('.tagline', { delay: 500 });
ScrollReveal().reveal('.punchline', { delay: 2000 });

Scrollama:

const scroller = scrollama();
scroller
  .setup({
    step: '.step',
    offset: 0.5,
  })
  .onStepEnter(response => {
    // trigger animation for this step
  });

ScrollReveal is more straightforward for simple reveal animations, while Scrollama provides more control for step-based scrollytelling. ScrollReveal's API is declarative and easy to use for basic animations, whereas Scrollama requires more setup but offers finer control over scroll-based events and progress tracking. Choose ScrollReveal for simple reveal effects and Scrollama for complex, narrative-driven scrollytelling experiences.

The javascript library for magical scroll interactions.

Pros of ScrollMagic

  • More feature-rich, offering advanced animation capabilities and scene management
  • Supports both scroll-based and timeline-based animations
  • Integrates well with popular animation libraries like GSAP

Cons of ScrollMagic

  • Steeper learning curve due to its extensive feature set
  • Larger file size, which may impact page load times
  • Less frequently updated compared to Scrollama

Code Comparison

ScrollMagic:

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

Scrollama:

const scroller = scrollama();
scroller
  .setup({
    step: '.step',
    offset: 0.5,
  })
  .onStepEnter(response => {
    // Animation logic here
  });

ScrollMagic offers more complex scene management and animation control, while Scrollama provides a simpler, more streamlined approach to scroll-based interactions. ScrollMagic is better suited for projects requiring intricate animations, whereas Scrollama excels in simplicity and ease of use for basic scroll-driven content.

26,486

Animate on scroll library

Pros of AOS

  • Simpler setup and usage, with predefined animations out of the box
  • Supports a wider range of browsers, including older versions
  • Offers more built-in animation options without additional configuration

Cons of AOS

  • Less flexible for custom scroll-based interactions
  • May have performance issues with a large number of animated elements
  • Limited control over scroll progress and trigger points

Code Comparison

AOS:

<div data-aos="fade-up" data-aos-duration="1000">
  <h1>Animated content</h1>
</div>

Scrollama:

const scroller = scrollama();
scroller
  .setup({
    step: '.step',
    offset: 0.5,
  })
  .onStepEnter(response => {
    // Custom animation logic here
  });

Summary

AOS is easier to implement for simple scroll-based animations, while Scrollama offers more control and flexibility for complex scroll-driven interactions. AOS is better suited for projects requiring quick implementation of predefined animations, whereas Scrollama excels in creating custom, precisely controlled scroll experiences. The choice between the two depends on the specific requirements of the project and the desired level of customization.

3,593

🚀 Performance focused, lightweight scroll animation library 🚀

Pros of Sal

  • Lightweight and dependency-free, making it easier to integrate into projects
  • Supports both scroll-based and observer-based animations
  • Offers more granular control over animation timing and easing

Cons of Sal

  • Less extensive documentation compared to Scrollama
  • Fewer built-in features for complex scroll-based interactions
  • Smaller community and fewer updates

Code Comparison

Sal:

sal({
  threshold: 0.5,
  once: false,
  animateClassName: 'animate'
});

Scrollama:

const scroller = scrollama();
scroller
  .setup({
    step: '.step',
    offset: 0.5,
  })
  .onStepEnter(response => {
    // Trigger animation
  });

Summary

Sal is a lightweight scroll animation library that offers simplicity and flexibility, while Scrollama provides a more robust set of features for scroll-based storytelling. Sal excels in basic scroll animations with minimal setup, whereas Scrollama is better suited for complex, data-driven scroll interactions. The choice between the two depends on the specific requirements of your project and the level of control you need over scroll-based animations.

🛤 Detection of elements in viewport & smooth scrolling with parallax.

Pros of Locomotive Scroll

  • Smooth scrolling with customizable easing and lerp
  • Parallax effects and horizontal scrolling support
  • Extensive API for advanced scroll-based animations

Cons of Locomotive Scroll

  • Steeper learning curve due to more complex API
  • Larger file size and potential performance impact
  • Less focus on storytelling and step-based scrollytelling

Code Comparison

Locomotive Scroll:

const scroll = new LocomotiveScroll({
  el: document.querySelector('[data-scroll-container]'),
  smooth: true,
  lerp: 0.1
});

scroll.on('scroll', (obj) => {
  // Handle scroll event
});

Scrollama:

const scroller = scrollama();

scroller
  .setup({
    step: '.step',
    offset: 0.5
  })
  .onStepEnter(response => {
    // Handle step enter
  });

Locomotive Scroll offers more advanced scrolling features and animations, while Scrollama focuses on simplicity and step-based scrollytelling. Locomotive Scroll is better suited for complex, visually-rich websites, whereas Scrollama excels in narrative-driven, step-by-step scroll experiences. The choice between the two depends on the specific project requirements and the desired level of scrolling complexity.

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

scrollama.js

Scrollama is a modern & lightweight JavaScript library for scrollytelling using IntersectionObserver in favor of scroll events. Current version: 3.2.0

3.0

Why 3.0?

The core parts of the Scrollama code base are being refactored for 3.0 to simplfy and clarify the logic. The goal behind this to ease make future maintainance, bug fixing, and feature additions easier moving forward.

New Fetaures

  • Built-in resize using resize observers.
  • Custom offsets on steps with data attributes

Deprecated Features

  • the order option

Important Changes

  • Version 3.0.0+: order has been deprecated.
  • Version 2.0.0+: .onContainerEnter and .onContainerExit have been deprecated in favor of CSS property position: sticky;. How to use position sticky.
  • Version 1.4.0+: you must manually add the IntersectionObserver polyfill for cross-browser support. See installation for details.

Jump to examples.

Why?

Scrollytelling can be complicated to implement and difficult to make performant. The goal of this library is to provide a simple interface for creating scroll-driven interactives. Scrollama is focused on performance by using IntersectionObserver to handle element position detection.

scrollytelling pattern

Examples

Note: most of these examples use D3 to keep the code concise, but this can be used with any library, or with no library at all.

  • Basic - just step triggers
  • Progress - incremental step progress callback
  • Sticky Graphic (Side by Side) - using CSS position: sticky; to create a fixed graphic to the side of the text.
  • Sticky Graphic (Overlay) - using CSS position: sticky; to create a fixed graphic with fullscreen graphic with text overlayed.
  • Custom Offset - Adding a data attribute to an element to provide a unique offset for a step.
  • Mobile Pattern - using pixels instead of percent for offset value so it doesn't jump around on scroll direction change
  • iframe Embed - Embedding a Scrollama instance inside an iframe using root option

Installation

Note: As of version 1.4.0, the IntersectionObserver polyfill has been removed from the build. You must include it yourself for cross-browser support. Check here to see if you need to include the polyfill.

Old school (exposes the scrollama global):

<script src="https://unpkg.com/scrollama"></script>

New school:

npm install scrollama intersection-observer --save

And then import/require it:

import scrollama from "scrollama"; // or...
const scrollama = require("scrollama");

How to use

Basic

You can use this library to simply trigger steps, similar to something like Waypoints. This is useful if you need more control over your interactive, or you don't want to follow the sticky scrollytelling pattern.

You can use any id/class naming conventions you want. The HTML structure should look like:

<!--you don't need the "data-step" attr, but can be useful for storing instructions for JS -->
<div class="step" data-step="a"></div>
<div class="step" data-step="b"></div>
<div class="step" data-step="c"></div>
// instantiate the scrollama
const scroller = scrollama();

// setup the instance, pass callback functions
scroller
  .setup({
    step: ".step",
  })
  .onStepEnter((response) => {
    // { element, index, direction }
  })
  .onStepExit((response) => {
    // { element, index, direction }
  });

API

scrollama.setup([options])

options:

OptionTypeDescriptionDefault
stepstring or HTMLElement[]required Selector (or array of elements) for the step elements that will trigger changes.
offsetnumber (0 - 1, or string with "px")How far from the top of the viewport to trigger a step.0.5
progressbooleanWhether to fire incremental step progress updates or not.false
thresholdnumber (1 or higher)The granularity of the progress interval in pixels (smaller = more granular).4
oncebooleanOnly trigger the step to enter once then remove listener.false
debugbooleanWhether to show visual debugging tools or not.false
parentHTMLElement[]Parent element for step selector (use if you steps are in shadow DOM).undefined
containerHTMLElementParent element for the scroll story (use if scrollama is nested in a HTML element with overflow set to scroll or auto)undefined
rootHTMLElementThe element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null. See more details about usage of root on MDN.undefined

scrollama.onStepEnter(callback)

Callback that fires when the top or bottom edge of a step element enters the offset threshold.

The argument of the callback is an object: { element: DOMElement, index: number, direction: string }

element: The step element that triggered

index: The index of the step of all steps

direction: 'up' or 'down'

scrollama.onStepExit(callback)

Callback that fires when the top or bottom edge of a step element exits the offset threshold.

The argument of the callback is an object: { element: DOMElement, index: number, direction: string }

element: The step element that triggered

index: The index of the step of all steps

direction: 'up' or 'down'

scrollama.onStepProgress(callback)

Callback that fires the progress (0 - 1) a step has made through the threshold.

The argument of the callback is an object: { element: DOMElement, index: number, progress: number }

element: The step element that triggered

index: The index of the step of all steps

progress: The percent of completion of the step (0 - 1)

direction: 'up' or 'down'

scrollama.offsetTrigger([number or string])

Get or set the offset percentage. Value must be between 0-1 (where 0 = top of viewport, 1 = bottom), or a string that includes "px" (e.g., "200px"). If set, returns the scrollama instance.

scrollama.resize()

This is no longer necessary with the addition of a built-in resize observer. Tell scrollama to get latest dimensions the browser/DOM. It is best practice to throttle resize in your code, update the DOM elements, then call this function at the end.

scrollama.enable()

Tell scrollama to resume observing for trigger changes. Only necessary to call if you have previously disabled.

scrollama.disable()

Tell scrollama to stop observing for trigger changes.

scrollama.destroy()

Removes all observers and callback functions.

custom offset

To override the offset passed in the options, set a custom offset for an individual element using data attributes. For example: <div class="step" data-offset="0.25"> or data-offset="100px".

Scrollama In The Wild

Tips

  • Avoid using viewport height (vh) in your CSS because scrolling up and down constantly triggers vh to change, which will also trigger a window resize.

Alternatives

Logo

Logo by the awesome Elaina Natario

License

MIT License

Copyright (c) 2022 Russell Samora

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days