├── .gitignore ├── .npm-ignore ├── LICENSE ├── README.md ├── build ├── scrollama.js └── scrollama.min.js ├── dev ├── d3.v4.min.js ├── enable-disable.html ├── fixed-js.html ├── index.html ├── multiple.html ├── overflow-scroll-error.html ├── progress.html └── scroll-parent.html ├── docs ├── .nojekyll ├── basic │ └── index.html ├── custom-offset │ └── index.html ├── iframe │ ├── basic.html │ └── index.html ├── index.html ├── logo.png ├── mobile-pattern │ └── index.html ├── progress │ └── index.html ├── scrollama.min.js ├── sticky-overlay │ └── index.html ├── sticky-side │ └── index.html └── style.css ├── index.d.ts ├── index.js ├── package.json ├── rollup.config.js └── src ├── createProgressThreshold.js ├── debug.js ├── dom.js ├── entry.js ├── err.js ├── generateId.js ├── getIndex.js ├── getOffsetTop.js ├── indexSteps.js ├── parseOffset.js └── scroll.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | package-lock.json -------------------------------------------------------------------------------- /.npm-ignore: -------------------------------------------------------------------------------- 1 | dev/ 2 | docs/ 3 | build/scrollama.js 4 | rollup.config.* 5 | .gitignore 6 | .travis.yml 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Russell Samora 4 | 5 | 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: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | scrollama.js 2 | 3 | **Scrollama** is a modern & lightweight JavaScript library for scrollytelling 4 | using 5 | [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) 6 | in favor of scroll events. *Current version: 3.2.0* 7 | 8 | ## 3.0 9 | #### Why 3.0? 10 | 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. 11 | 12 | #### New Fetaures 13 | * Built-in resize using resize observers. 14 | * Custom offsets on steps with data attributes 15 | 16 | #### Deprecated Features 17 | * the `order` option 18 | 19 | ## Important Changes 20 | - **Version 3.0.0+**: `order` has been deprecated. 21 | - **Version 2.0.0+**: `.onContainerEnter` and `.onContainerExit` have been deprecated in favor of CSS property `position: sticky;`. [How to use position sticky.](https://pudding.cool/process/scrollytelling-sticky/) 22 | - **Version 1.4.0+**: you must manually add the IntersectionObserver polyfill for cross-browser support. See [installation](https://github.com/russellsamora/scrollama#installation) for details. 23 | 24 | [Jump to examples.](https://github.com/russellsamora/scrollama#examples) 25 | 26 | ## Why? 27 | 28 | Scrollytelling can be complicated to implement and difficult to make performant. 29 | The goal of this library is to provide a simple interface for creating 30 | scroll-driven interactives. Scrollama is focused on performance by using 31 | [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) 32 | to handle element position detection. 33 | 34 | [![scrollytelling pattern](https://thumbs.gfycat.com/FearfulHotArabianoryx-size_restricted.gif)](https://pudding.cool/process/how-to-implement-scrollytelling) 35 | 36 | ## Examples 37 | 38 | _Note: most of these examples use D3 to keep the code concise, but this can be used 39 | with any library, or with no library at all._ 40 | 41 | - [Basic](https://russellsamora.github.io/scrollama/basic) - just step 42 | triggers 43 | - [Progress](https://russellsamora.github.io/scrollama/progress) - 44 | incremental step progress callback 45 | - [Sticky Graphic (Side by Side)](https://russellsamora.github.io/scrollama/sticky-side) - 46 | using CSS `position: sticky;` to create a fixed graphic to the side of the text. 47 | - [Sticky Graphic (Overlay)](https://russellsamora.github.io/scrollama/sticky-overlay) - 48 | using CSS `position: sticky;` to create a fixed graphic with fullscreen graphic with text overlayed. 49 | - [Custom Offset](https://russellsamora.github.io/scrollama/custom-offset) - 50 | Adding a data attribute to an element to provide a unique offset for a step. 51 | - [Mobile Pattern](https://russellsamora.github.io/scrollama/mobile-pattern) - 52 | using pixels instead of percent for offset value so it doesn't jump around on scroll direction change 53 | - [iframe Embed](https://russellsamora.github.io/scrollama/iframe) - 54 | Embedding a Scrollama instance inside an iframe using `root` option 55 | 56 | ## Installation 57 | **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](https://caniuse.com/#feat=intersectionobserver) to see if you need to include the polyfill. 58 | 59 | Old school (exposes the `scrollama` global): 60 | 61 | ```html 62 | 63 | ``` 64 | 65 | New school: 66 | 67 | ```sh 68 | npm install scrollama intersection-observer --save 69 | ``` 70 | 71 | And then import/require it: 72 | 73 | ```js 74 | import scrollama from "scrollama"; // or... 75 | const scrollama = require("scrollama"); 76 | ``` 77 | 78 | ## How to use 79 | 80 | #### Basic 81 | 82 | You can use this library to simply trigger steps, similar to something like 83 | [Waypoints](http://imakewebthings.com/waypoints/). This is useful if you need 84 | more control over your interactive, or you don't want to follow the sticky 85 | scrollytelling pattern. 86 | 87 | You can use any id/class naming conventions you want. The HTML structure should 88 | look like: 89 | 90 | ```html 91 | 92 |
93 |
94 |
95 | ``` 96 | 97 | ```js 98 | // instantiate the scrollama 99 | const scroller = scrollama(); 100 | 101 | // setup the instance, pass callback functions 102 | scroller 103 | .setup({ 104 | step: ".step", 105 | }) 106 | .onStepEnter((response) => { 107 | // { element, index, direction } 108 | }) 109 | .onStepExit((response) => { 110 | // { element, index, direction } 111 | }); 112 | ``` 113 | 114 | ## API 115 | 116 | #### scrollama.setup([options]) 117 | 118 | _options:_ 119 | 120 | | Option | Type | Description | Default | 121 | | --- | --- | --- | --- | 122 | | step | string or HTMLElement[] | **required** Selector (or array of elements) for the step elements that will trigger changes. | 123 | | offset | number (0 - 1, or string with "px") | How far from the top of the viewport to trigger a step. | 0.5 | 124 | | progress | boolean | Whether to fire incremental step progress updates or not. | false | 125 | | threshold | number (1 or higher) | The granularity of the progress interval in pixels (smaller = more granular). | 4 | 126 | | once | boolean | Only trigger the step to enter once then remove listener. | false || 127 | | debug | boolean | Whether to show visual debugging tools or not. | false | 128 | | parent | HTMLElement[] | Parent element for step selector (use if you steps are in shadow DOM). | undefined | 129 | | container | HTMLElement | Parent element for the scroll story (use if scrollama is nested in a HTML element with overflow set to `scroll` or `auto`) | undefined | 130 | | root | HTMLElement | The 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](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#intersection_observer_concepts_and_usage). | undefined | 131 | 132 | #### scrollama.onStepEnter(callback) 133 | 134 | Callback that fires when the top or bottom edge of a step element enters the 135 | offset threshold. 136 | 137 | The argument of the callback is an object: `{ element: DOMElement, index: number, direction: string }` 138 | 139 | `element`: The step element that triggered 140 | 141 | `index`: The index of the step of all steps 142 | 143 | `direction`: 'up' or 'down' 144 | 145 | #### scrollama.onStepExit(callback) 146 | 147 | Callback that fires when the top or bottom edge of a step element exits the 148 | offset threshold. 149 | 150 | The argument of the callback is an object: `{ element: DOMElement, index: number, direction: string }` 151 | 152 | `element`: The step element that triggered 153 | 154 | `index`: The index of the step of all steps 155 | 156 | `direction`: 'up' or 'down' 157 | 158 | #### scrollama.onStepProgress(callback) 159 | 160 | Callback that fires the progress (0 - 1) a step has made through the threshold. 161 | 162 | The argument of the callback is an object: `{ element: DOMElement, index: number, progress: number }` 163 | 164 | `element`: The step element that triggered 165 | 166 | `index`: The index of the step of all steps 167 | 168 | `progress`: The percent of completion of the step (0 - 1) 169 | 170 | `direction`: 'up' or 'down' 171 | 172 | #### scrollama.offsetTrigger([number or string]) 173 | 174 | 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. 175 | 176 | #### scrollama.resize() 177 | 178 | **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 179 | throttle resize in your code, update the DOM elements, then call this function 180 | at the end. 181 | 182 | #### scrollama.enable() 183 | 184 | Tell scrollama to resume observing for trigger changes. Only necessary to call 185 | if you have previously disabled. 186 | 187 | #### scrollama.disable() 188 | 189 | Tell scrollama to stop observing for trigger changes. 190 | 191 | #### scrollama.destroy() 192 | 193 | Removes all observers and callback functions. 194 | 195 | #### custom offset 196 | 197 | To override the offset passed in the options, set a custom offset for an individual element using data attributes. For example: `
` or `data-offset="100px"`. 198 | 199 | ## Scrollama In The Wild 200 | * [The Billionaire Playbook - ProPublica](https://www.propublica.org/article/the-billionaire-playbook-how-sports-owners-use-their-teams-to-avoid-millions-in-taxes) 201 | * [Women's Pockets are Inferior - The Pudding](https://pudding.cool/2018/08/pockets/) 202 | * [Trump approval rating - Politico](https://www.politico.com/interactives/2019/trump-approval-rating-polls/) 203 | * [How the opioid epidemic evolved - Washington Post](https://www.washingtonpost.com/graphics/2019/investigations/opioid-pills-overdose-analysis/) 204 | * [US Covid-19 deaths, explained in 8 charts and maps - Vox](https://www.vox.com/22252693/covid-19-deaths-us-who-died) 205 | * [Life After Death on Wikipedia - The Pudding](https://pudding.cool/2018/08/wiki-death/) 206 | * [YouTube With Me - YouTube](https://youtube.com/trends/articles/with-me-interactive/) 207 | * [Unchecked Power - ProPublica](https://projects.propublica.org/nypd-unchecked-power/) 208 | * [Trump's environmental policies rule only part of America - Politico](https://www.politico.com/interactives/2018/trump-environmental-policies-rollbacks/) 209 | * [The story of New Zealand’s Covid-19 lockdown, in graphs - Stuff](https://interactives.stuff.co.nz/2020/05/coronavirus-covid-19-data-new-zealand/) 210 | * [Trump and Biden's Paths to Victory in the 2020 Election - Wall Street Journal](https://www.wsj.com/graphics/the-paths-to-victory/) 211 | * [The sicence of superspreading - Science](https://vis.sciencemag.org/covid-clusters/) 212 | * [El dominio histórico de la derecha en Madrid - elDiario.es](https://www.eldiario.es/madrid/gana-derecha-elecciones-madrid-mayoritaria-30-rico_1_7347696.html) 213 | * [The Permutation Test - Jared Wilber](https://www.jwilber.me/permutationtest/) 214 | * [Constellations - Nadieh Bremer](https://nbremer.github.io/planet-constellations/) 215 | * [Remote Triggering of Earthquakes - Will Chase](https://www.williamrchase.com/vizrisk/vizrisk_main/) 216 | * [Scrollytelling - Mapbox](https://demos.mapbox.com/scrollytelling/) 217 | 218 | ## Tips 219 | - 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. 220 | 221 | ## Alternatives 222 | - [Scroll Trigger](https://greensock.com/scrolltrigger/) 223 | - [Waypoints](http://imakewebthings.com/waypoints/) 224 | - [ScrollMagic](http://scrollmagic.io/) 225 | - [graph-scroll.js](https://1wheel.github.io/graph-scroll/) 226 | - [ScrollStory](https://sjwilliams.github.io/scrollstory/) 227 | - [enter-view](https://github.com/russellsamora/enter-view) 228 | 229 | ## Logo 230 | 231 | Logo by the awesome [Elaina Natario](https://twitter.com/elainanatario) 232 | 233 | ## License 234 | 235 | MIT License 236 | 237 | Copyright (c) 2022 Russell Samora 238 | 239 | Permission is hereby granted, free of charge, to any person obtaining a copy of 240 | this software and associated documentation files (the "Software"), to deal in 241 | the Software without restriction, including without limitation the rights to 242 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 243 | the Software, and to permit persons to whom the Software is furnished to do so, 244 | subject to the following conditions: 245 | 246 | The above copyright notice and this permission notice shall be included in all 247 | copies or substantial portions of the Software. 248 | 249 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 250 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 251 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 252 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 253 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 254 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 255 | -------------------------------------------------------------------------------- /build/scrollama.js: -------------------------------------------------------------------------------- 1 | (function (global, factory) { 2 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 3 | typeof define === 'function' && define.amd ? define(factory) : 4 | (global = global || self, global.scrollama = factory()); 5 | }(this, (function () { 'use strict'; 6 | 7 | // DOM helper functions 8 | 9 | // public 10 | function selectAll(selector, parent = document) { 11 | if (typeof selector === 'string') { 12 | return Array.from(parent.querySelectorAll(selector)); 13 | } else if (selector instanceof Element) { 14 | return [selector]; 15 | } else if (selector instanceof NodeList) { 16 | return Array.from(selector); 17 | } else if (selector instanceof Array) { 18 | return selector; 19 | } 20 | return []; 21 | } 22 | 23 | // SETUP 24 | function create(className) { 25 | const el = document.createElement("div"); 26 | el.className = `scrollama__debug-step ${className}`; 27 | el.style.position = "fixed"; 28 | el.style.left = "0"; 29 | el.style.width = "100%"; 30 | el.style.zIndex = "9999"; 31 | el.style.borderTop = "2px solid black"; 32 | el.style.borderBottom = "2px solid black"; 33 | 34 | const p = document.createElement("p"); 35 | p.style.position = "absolute"; 36 | p.style.left = "0"; 37 | p.style.height = "1px"; 38 | p.style.width = "100%"; 39 | p.style.borderTop = "1px dashed black"; 40 | 41 | el.appendChild(p); 42 | document.body.appendChild(el); 43 | return el; 44 | } 45 | 46 | // UPDATE 47 | function update({ id, step, marginTop }) { 48 | const { index, height } = step; 49 | const className = `scrollama__debug-step--${id}-${index}`; 50 | let el = document.querySelector(`.${className}`); 51 | if (!el) el = create(className); 52 | 53 | el.style.top = `${marginTop * -1}px`; 54 | el.style.height = `${height}px`; 55 | el.querySelector("p").style.top = `${height / 2}px`; 56 | } 57 | 58 | function generateId() { 59 | const alphabet = "abcdefghijklmnopqrstuvwxyz"; 60 | const date = Date.now(); 61 | const result = []; 62 | for (let i = 0; i < 6; i += 1) { 63 | const char = alphabet[Math.floor(Math.random() * alphabet.length)]; 64 | result.push(char); 65 | } 66 | return `${result.join("")}${date}`; 67 | } 68 | 69 | function err$1(msg) { 70 | console.error(`scrollama error: ${msg}`); 71 | } 72 | 73 | function getIndex(node) { 74 | return +node.getAttribute("data-scrollama-index"); 75 | } 76 | 77 | function createProgressThreshold(height, threshold) { 78 | const count = Math.ceil(height / threshold); 79 | const t = []; 80 | const ratio = 1 / count; 81 | for (let i = 0; i < count + 1; i += 1) { 82 | t.push(i * ratio); 83 | } 84 | return t; 85 | } 86 | 87 | function parseOffset(x) { 88 | if (typeof x === "string" && x.indexOf("px") > 0) { 89 | const v = +x.replace("px", ""); 90 | if (!isNaN(v)) return { format: "pixels", value: v }; 91 | else { 92 | err("offset value must be in 'px' format. Fallback to 0.5."); 93 | return { format: "percent", value: 0.5 }; 94 | } 95 | } else if (typeof x === "number" || !isNaN(+x)) { 96 | if (x > 1) err("offset value is greater than 1. Fallback to 1."); 97 | if (x < 0) err("offset value is lower than 0. Fallback to 0."); 98 | return { format: "percent", value: Math.min(Math.max(0, x), 1) }; 99 | } 100 | return null; 101 | } 102 | 103 | function indexSteps(steps) { 104 | steps.forEach((step) => 105 | step.node.setAttribute("data-scrollama-index", step.index) 106 | ); 107 | } 108 | 109 | function getOffsetTop(node) { 110 | const { top } = node.getBoundingClientRect(); 111 | const scrollTop = window.pageYOffset; 112 | const clientTop = document.body.clientTop || 0; 113 | return top + scrollTop - clientTop; 114 | } 115 | 116 | let currentScrollY; 117 | let comparisonScrollY; 118 | let direction; 119 | 120 | function onScroll(container) { 121 | const scrollTop = container ? container.scrollTop : window.pageYOffset; 122 | 123 | if (currentScrollY === scrollTop) return; 124 | currentScrollY = scrollTop; 125 | if (currentScrollY > comparisonScrollY) direction = "down"; 126 | else if (currentScrollY < comparisonScrollY) direction = "up"; 127 | comparisonScrollY = currentScrollY; 128 | } 129 | 130 | function setupScroll(container) { 131 | currentScrollY = 0; 132 | comparisonScrollY = 0; 133 | document.addEventListener("scroll", () => onScroll(container)); 134 | } 135 | 136 | function scrollama() { 137 | let cb = {}; 138 | 139 | let id = generateId(); 140 | let steps = []; 141 | let globalOffset; 142 | let containerElement; 143 | let rootElement; 144 | 145 | let progressThreshold = 0; 146 | 147 | let isEnabled = false; 148 | let isProgress = false; 149 | let isDebug = false; 150 | let isTriggerOnce = false; 151 | 152 | let exclude = []; 153 | 154 | /* HELPERS */ 155 | function reset() { 156 | cb = { 157 | stepEnter: () => { }, 158 | stepExit: () => { }, 159 | stepProgress: () => { }, 160 | }; 161 | exclude = []; 162 | } 163 | 164 | function handleEnable(shouldEnable) { 165 | if (shouldEnable && !isEnabled) updateObservers(); 166 | if (!shouldEnable && isEnabled) disconnectObservers(); 167 | isEnabled = shouldEnable; 168 | } 169 | 170 | /* NOTIFY CALLBACKS */ 171 | function notifyProgress(element, progress) { 172 | const index = getIndex(element); 173 | const step = steps[index]; 174 | if (progress !== undefined) step.progress = progress; 175 | const response = { element, index, progress, direction }; 176 | if (step.state === "enter") cb.stepProgress(response); 177 | } 178 | 179 | function notifyStepEnter(element, check = true) { 180 | const index = getIndex(element); 181 | const step = steps[index]; 182 | const response = { element, index, direction }; 183 | 184 | step.direction = direction; 185 | step.state = "enter"; 186 | 187 | // if (isPreserveOrder && check && direction !== "up") 188 | // notifyOthers(index, "above"); 189 | // if (isPreserveOrder && check && direction === "up") 190 | // notifyOthers(index, "below"); 191 | 192 | if (!exclude[index]) cb.stepEnter(response); 193 | if (isTriggerOnce) exclude[index] = true; 194 | } 195 | 196 | function notifyStepExit(element, check = true) { 197 | const index = getIndex(element); 198 | const step = steps[index]; 199 | 200 | if (!step.state) return false; 201 | 202 | const response = { element, index, direction }; 203 | 204 | if (isProgress) { 205 | if (direction === "down" && step.progress < 1) notifyProgress(element, 1); 206 | else if (direction === "up" && step.progress > 0) 207 | notifyProgress(element, 0); 208 | } 209 | 210 | step.direction = direction; 211 | step.state = "exit"; 212 | 213 | cb.stepExit(response); 214 | } 215 | 216 | /* OBSERVERS - HANDLING */ 217 | function resizeStep([entry]) { 218 | const index = getIndex(entry.target); 219 | const step = steps[index]; 220 | const h = entry.target.offsetHeight; 221 | if (h !== step.height) { 222 | step.height = h; 223 | disconnectObserver(step); 224 | updateStepObserver(step); 225 | updateResizeObserver(step); 226 | } 227 | } 228 | 229 | function intersectStep([entry]) { 230 | onScroll(containerElement); 231 | 232 | const { isIntersecting, target } = entry; 233 | if (isIntersecting) notifyStepEnter(target); 234 | else notifyStepExit(target); 235 | } 236 | 237 | function intersectProgress([entry]) { 238 | const index = getIndex(entry.target); 239 | const step = steps[index]; 240 | const { isIntersecting, intersectionRatio, target } = entry; 241 | if (isIntersecting && step.state === "enter") 242 | notifyProgress(target, intersectionRatio); 243 | } 244 | 245 | /* OBSERVERS - CREATION */ 246 | function disconnectObserver({ observers }) { 247 | Object.keys(observers).map((name) => { 248 | observers[name].disconnect(); 249 | }); 250 | } 251 | 252 | function disconnectObservers() { 253 | steps.forEach(disconnectObserver); 254 | } 255 | 256 | function updateResizeObserver(step) { 257 | const observer = new ResizeObserver(resizeStep); 258 | observer.observe(step.node); 259 | step.observers.resize = observer; 260 | } 261 | 262 | function updateResizeObservers() { 263 | steps.forEach(updateResizeObserver); 264 | } 265 | 266 | function updateStepObserver(step) { 267 | const h = window.innerHeight; 268 | const off = step.offset || globalOffset; 269 | const factor = off.format === "pixels" ? 1 : h; 270 | const offset = off.value * factor; 271 | const marginTop = step.height / 2 - offset; 272 | const marginBottom = step.height / 2 - (h - offset); 273 | const rootMargin = `${marginTop}px 0px ${marginBottom}px 0px`; 274 | const root = rootElement; 275 | 276 | const threshold = 0.5; 277 | const options = { rootMargin, threshold, root }; 278 | const observer = new IntersectionObserver(intersectStep, options); 279 | 280 | observer.observe(step.node); 281 | step.observers.step = observer; 282 | 283 | if (isDebug) update({ id, step, marginTop, marginBottom }); 284 | } 285 | 286 | function updateStepObservers() { 287 | steps.forEach(updateStepObserver); 288 | } 289 | 290 | function updateProgressObserver(step) { 291 | const h = window.innerHeight; 292 | const off = step.offset || globalOffset; 293 | const factor = off.format === "pixels" ? 1 : h; 294 | const offset = off.value * factor; 295 | const marginTop = -offset + step.height; 296 | const marginBottom = offset - h; 297 | const rootMargin = `${marginTop}px 0px ${marginBottom}px 0px`; 298 | 299 | const threshold = createProgressThreshold(step.height, progressThreshold); 300 | const options = { rootMargin, threshold }; 301 | const observer = new IntersectionObserver(intersectProgress, options); 302 | 303 | observer.observe(step.node); 304 | step.observers.progress = observer; 305 | } 306 | 307 | function updateProgressObservers() { 308 | steps.forEach(updateProgressObserver); 309 | } 310 | 311 | function updateObservers() { 312 | disconnectObservers(); 313 | updateResizeObservers(); 314 | updateStepObservers(); 315 | if (isProgress) updateProgressObservers(); 316 | } 317 | 318 | /* SETUP */ 319 | const S = {}; 320 | 321 | S.setup = ({ 322 | step, 323 | parent, 324 | offset = 0.5, 325 | threshold = 4, 326 | progress = false, 327 | once = false, 328 | debug = false, 329 | container = undefined, 330 | root = null 331 | }) => { 332 | 333 | setupScroll(container); 334 | 335 | steps = selectAll(step, parent).map((node, index) => ({ 336 | index, 337 | direction: undefined, 338 | height: node.offsetHeight, 339 | node, 340 | observers: {}, 341 | offset: parseOffset(node.dataset.offset), 342 | top: getOffsetTop(node), 343 | progress: 0, 344 | state: undefined, 345 | })); 346 | 347 | if (!steps.length) { 348 | err$1("no step elements"); 349 | return S; 350 | } 351 | 352 | isProgress = progress; 353 | isTriggerOnce = once; 354 | isDebug = debug; 355 | progressThreshold = Math.max(1, +threshold); 356 | globalOffset = parseOffset(offset); 357 | containerElement = container; 358 | rootElement = root; 359 | 360 | reset(); 361 | indexSteps(steps); 362 | handleEnable(true); 363 | return S; 364 | }; 365 | 366 | S.enable = () => { 367 | handleEnable(true); 368 | return S; 369 | }; 370 | 371 | S.disable = () => { 372 | handleEnable(false); 373 | return S; 374 | }; 375 | 376 | S.destroy = () => { 377 | handleEnable(false); 378 | reset(); 379 | return S; 380 | }; 381 | 382 | S.resize = () => { 383 | updateObservers(); 384 | return S; 385 | }; 386 | 387 | S.offset = (x) => { 388 | if (x === null || x === undefined) return globalOffset.value; 389 | globalOffset = parseOffset(x); 390 | updateObservers(); 391 | return S; 392 | }; 393 | 394 | S.onStepEnter = (f) => { 395 | if (typeof f === "function") cb.stepEnter = f; 396 | else err$1("onStepEnter requires a function"); 397 | return S; 398 | }; 399 | 400 | S.onStepExit = (f) => { 401 | if (typeof f === "function") cb.stepExit = f; 402 | else err$1("onStepExit requires a function"); 403 | return S; 404 | }; 405 | 406 | S.onStepProgress = (f) => { 407 | if (typeof f === "function") cb.stepProgress = f; 408 | else err$1("onStepProgress requires a function"); 409 | return S; 410 | }; 411 | return S; 412 | } 413 | 414 | return scrollama; 415 | 416 | }))); 417 | -------------------------------------------------------------------------------- /build/scrollama.min.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).scrollama=t()}(this,function(){"use strict";function k({id:e,step:t,marginTop:o}){var{index:n,height:t}=t,n=`scrollama__debug-step--${e}-${n}`;let r=document.querySelector(`.${n}`);r=r||function(e){const t=document.createElement("div");t.className=`scrollama__debug-step ${e}`,t.style.position="fixed",t.style.left="0",t.style.width="100%",t.style.zIndex="9999",t.style.borderTop="2px solid black",t.style.borderBottom="2px solid black";const o=document.createElement("p");return o.style.position="absolute",o.style.left="0",o.style.height="1px",o.style.width="100%",o.style.borderTop="1px dashed black",t.appendChild(o),document.body.appendChild(t),t}(n),r.style.top=`${-1*o}px`,r.style.height=`${t}px`,r.querySelector("p").style.top=`${t/2}px`}function M(e){console.error(`scrollama error: ${e}`)}function q(e){return+e.getAttribute("data-scrollama-index")}function O(e){if("string"==typeof e&&0N?T="down":A{},stepExit:()=>{},stepProgress:()=>{}},n=[]}function b(e){e&&!t&&$(),!e&&t&&y(),t=e}function s(e,t){var o=q(e);const n=f[o];void 0!==t&&(n.progress=t);t={element:e,index:o,progress:t,direction:T};"enter"===n.state&&r.stepProgress(t)}function o([e]){var t=q(e.target);const o=f[t];e=e.target.offsetHeight;e!==o.height&&(o.height=e,l(o),w(o),E(o))}function a([e]){z(u);var{isIntersecting:t,target:e}=e;(t?function(e){var t=q(e);const o=f[t];e={element:e,index:t,direction:T},o.direction=T,o.state="enter",n[t]||r.stepEnter(e),v&&(n[t]=!0)}:function(e){var t=q(e);const o=f[t];o.state&&(t={element:e,index:t,direction:T},g&&("down"===T&&o.progress<1?s(e,1):"up"===T&&0{t[e].disconnect()})}function y(){f.forEach(l)}function E(e){const t=new ResizeObserver(o);t.observe(e.node),e.observers.resize=t}function w(e){var t=window.innerHeight,o=e.offset||p,n="pixels"===o.format?1:t,r=o.value*n,o=e.height/2-r,n=e.height/2-(t-r),t=`${o}px 0px ${n}px 0px`,r=d;const s=new IntersectionObserver(a,{rootMargin:t,threshold:.5,root:r});s.observe(e.node),e.observers.step=s,m&&k({id:i,step:e,marginTop:o,marginBottom:n})}function e(e){var t=window.innerHeight,o=e.offset||p,n="pixels"===o.format?1:t,n=o.value*n,n=`${-n+e.height}px 0px ${n-t}px 0px`,t=function(e,t){var o=Math.ceil(e/t);const n=[];var r=1/o;for(let e=0;e{var l;return l=a,A=0,N=0,document.addEventListener("scroll",()=>z(l)),f=([e,t=document]=[e,t],("string"==typeof e?Array.from(t.querySelectorAll(e)):e instanceof Element?[e]:e instanceof NodeList?Array.from(e):e instanceof Array?e:[]).map((e,t)=>({index:t,direction:void 0,height:e.offsetHeight,node:e,observers:{},offset:O(e.dataset.offset),top:function(e){var{top:e}=e.getBoundingClientRect();return e+window.pageYOffset-(document.body.clientTop||0)}(e),progress:0,state:void 0}))),f.length?(g=r,v=s,m=i,h=Math.max(1,+n),p=O(o),u=a,d=c,x(),f.forEach(e=>e.node.setAttribute("data-scrollama-index",e.index)),b(!0)):M("no step elements"),S},S.enable=()=>(b(!0),S),S.disable=()=>(b(!1),S),S.destroy=()=>(b(!1),x(),S),S.resize=()=>($(),S),S.offset=e=>null==e?p.value:(p=O(e),$(),S),S.onStepEnter=e=>("function"==typeof e?r.stepEnter=e:M("onStepEnter requires a function"),S),S.onStepExit=e=>("function"==typeof e?r.stepExit=e:M("onStepExit requires a function"),S),S.onStepProgress=e=>("function"==typeof e?r.stepProgress=e:M("onStepProgress requires a function"),S),S}}); 2 | -------------------------------------------------------------------------------- /dev/enable-disable.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama Demo: Enable/Disable 8 | 9 | 10 | 114 | 115 | 116 | 117 |
118 |

119 | scrollama.js 120 |

121 |

Demo: Enable & Disable Events

122 |

123 | Start scrolling to see how it works. Click below to enable or disable 124 | the scroller. 125 |

126 | 127 |
128 |
129 |
130 |
131 |

STEP 1

132 |
133 |
134 |

STEP 2

135 |
136 |
137 |
138 |
139 | 140 | 141 | 142 | 215 | 216 | 217 | -------------------------------------------------------------------------------- /dev/fixed-js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama Demo: Fixed JS 8 | 9 | 10 | 145 | 146 | 147 | 148 |
149 |

150 | scrollama.js 151 |

152 |

Demo: Sticky Graphic Position

153 |

154 | Start scrolling to see how it works. 155 |

156 |
157 |
158 |
159 |
160 |

STEP 1

161 |
162 |
163 |

STEP 2

164 |
165 |
166 |

STEP 3

167 |
168 |
169 |

STEP 4

170 |
171 |
172 |
173 |

0

174 |
175 |
176 |
177 | 178 | 179 | 180 | 241 | 242 | 243 | -------------------------------------------------------------------------------- /dev/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Basic Example 8 | 9 | 10 | 11 | 40 | 41 | 42 | 43 |
44 |
45 |

Basic Example

46 |

47 | Start scrolling to see how it works. 48 |

49 |
50 |
51 |
52 |
53 |

STEP 1

54 |
55 |
56 |

STEP 2

57 |
58 |
59 |

STEP 3

60 |
61 |
62 |

STEP 4

63 |
64 |
65 |
66 |
67 |
68 | 69 | 70 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /dev/multiple.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | Scrollama demo 13 | 14 | 15 | 92 | 93 | 94 | 95 |
96 |
97 |
98 |

Step 1

99 |
100 | 103 | 109 |
110 |
111 |
112 |
113 |
114 |

Step 1

115 |
116 | 119 | 125 |
126 |
127 |
128 | 129 | 130 | 131 | 232 | 233 | 234 | -------------------------------------------------------------------------------- /dev/overflow-scroll-error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama Demo: Basic 8 | 9 | 10 | 125 | 126 | 127 | 128 |
129 |
130 |

131 | scrollama.js 132 |

133 |

134 | Scrollama throws an error when steps are children of a scrollable 135 | element 136 |

137 |

138 | Calculating the scroll direction is problematic when steps are 139 | children of a scrollable element that isn't the page scroll. This page 140 | provides an example of what not to do: 141 | do NOT place steps inside a scrollable element with 142 | overflowY: scroll or overflowY: auto and fixed 143 | height. 144 |

145 |

To demonstrate the incorrect behavior:

146 |
    147 |
  • 148 | ensure that the olive-colored element intersects the trigger (the 149 | dotted line) 150 |
  • 151 |
  • move the mouse pointer inside the olive-colored element
  • 152 |
  • 153 | scroll up and down with the mouse pointer inside the colored 154 | container. You may have to scroll up and down several times before 155 | the direction calculation becomes incorrect 156 |
  • 157 |
158 |

159 | Notice that step events are not triggered correctly when the inner 160 | container scrolls without the window element scrolling. 161 |

162 |
163 |
164 | 165 | 166 | 167 | 168 | 250 | 251 | 252 | -------------------------------------------------------------------------------- /dev/progress.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama Demo: Basic 8 | 9 | 10 | 109 | 110 | 111 | 112 |
113 |

114 | scrollama.js 115 |

116 |

Demo: Basic

117 |

118 | Start scrolling to see how it works. 119 |

120 |
121 |
122 |
123 |
124 |

STEP 1

125 |
126 |
127 |

STEP 2

128 |
129 |
130 |
131 |
132 | 133 | 134 | 192 | 193 | 194 | -------------------------------------------------------------------------------- /dev/scroll-parent.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Basic Example 8 | 9 | 10 | 53 | 54 | 55 | 56 | 57 |
58 | 69 |
70 | 81 |
82 |

Basic Example

83 |

84 | Start scrolling to see how it works. 85 |

86 |
87 |
88 |
89 |
90 |

STEP 1

91 |
92 |
93 |

STEP 2

94 |
95 |
96 |

STEP 3

97 |
98 |
99 |

STEP 4

100 |
101 |
102 |
103 |
104 |
105 |
106 | 107 | 108 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/russellsamora/scrollama/33731a160f2df3f2bde33a22b366bc0281777dbb/docs/.nojekyll -------------------------------------------------------------------------------- /docs/basic/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Basic Example 8 | 9 | 10 | 11 | 40 | 41 | 42 | 43 | 54 |
55 | 66 |
67 |

Basic Example

68 |

69 | Start scrolling to see how it works. 70 |

71 |
72 |
73 |
74 |
75 |

STEP 1

76 |
77 |
78 |

STEP 2

79 |
80 |
81 |

STEP 3

82 |
83 |
84 |

STEP 4

85 |
86 |
87 |
88 |
89 |
90 | 91 | 92 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /docs/custom-offset/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Custom Offset Example 8 | 9 | 10 | 11 | 40 | 41 | 42 | 43 | 54 |
55 | 66 |
67 |

Basic Example

68 |

69 | Start scrolling to see how it works. 70 |

71 |
72 |
73 |
74 |
75 |

STEP 1 - default (50%) offset

76 |
77 |
78 |

STEP 2 - 80% offset

79 |
80 |
81 |

STEP 3 - 20% offset

82 |
83 |
84 |

STEP 1 - default (50%) offset

85 |
86 |
87 |
88 |
89 |
90 | 91 | 92 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /docs/iframe/basic.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Basic Example 8 | 9 | 10 | 11 | 40 | 41 | 42 | 43 |
44 |
45 |

Basic Example

46 |

47 | Start scrolling to see how it works. 48 |

49 |
50 |
51 |
52 |
53 |

STEP 1

54 |
55 |
56 |

STEP 2

57 |
58 |
59 |

STEP 3

60 |
61 |
62 |

STEP 4

63 |
64 |
65 |
66 |
67 |
68 | 69 | 70 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /docs/iframe/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: iframe Example 8 | 9 | 10 | 11 | 40 | 41 | 42 | 43 | 54 |
55 | 67 |
68 |

iframe Example

69 |

70 | An example of embedding a Scrollama instance into an iframe. 71 |

72 |
73 |
74 | 76 |
77 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /docs/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/russellsamora/scrollama/33731a160f2df3f2bde33a22b366bc0281777dbb/docs/logo.png -------------------------------------------------------------------------------- /docs/mobile-pattern/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Mobile Pattern Example 8 | 9 | 10 | 11 | 40 | 41 | 42 | 43 | 54 |
55 | 66 |
67 |

Mobile Pattern Example

68 |

69 | Start scrolling to see how it works. 70 |

71 |
72 |
73 |
74 |
75 |

STEP 1

76 |
77 |
78 |

STEP 2

79 |
80 |
81 |

STEP 3

82 |
83 |
84 |

STEP 4

85 |
86 |
87 |
88 |
89 |
90 | 91 | 92 | 142 | 143 | 144 | -------------------------------------------------------------------------------- /docs/progress/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Progress Example 8 | 9 | 10 | 11 | 35 | 36 | 37 | 38 | 49 |
50 | 61 |
62 |

Progress Example

63 |

64 | Start scrolling to see how it works. 65 |

66 |
67 |
68 |
69 |
70 |

STEP 1

71 |

0%

72 |
73 |
74 |

STEP 2

75 |

0%

76 |
77 |
78 |
79 |
80 |
81 | 82 | 83 | 84 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /docs/scrollama.min.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).scrollama=t()}(this,function(){"use strict";function k({id:e,step:t,marginTop:o}){var{index:n,height:t}=t,n=`scrollama__debug-step--${e}-${n}`;let r=document.querySelector(`.${n}`);r=r||function(e){const t=document.createElement("div");t.className=`scrollama__debug-step ${e}`,t.style.position="fixed",t.style.left="0",t.style.width="100%",t.style.zIndex="9999",t.style.borderTop="2px solid black",t.style.borderBottom="2px solid black";const o=document.createElement("p");return o.style.position="absolute",o.style.left="0",o.style.height="1px",o.style.width="100%",o.style.borderTop="1px dashed black",t.appendChild(o),document.body.appendChild(t),t}(n),r.style.top=`${-1*o}px`,r.style.height=`${t}px`,r.querySelector("p").style.top=`${t/2}px`}function M(e){console.error(`scrollama error: ${e}`)}function q(e){return+e.getAttribute("data-scrollama-index")}function O(e){if("string"==typeof e&&0N?T="down":A{},stepExit:()=>{},stepProgress:()=>{}},n=[]}function b(e){e&&!t&&$(),!e&&t&&y(),t=e}function s(e,t){var o=q(e);const n=f[o];void 0!==t&&(n.progress=t);t={element:e,index:o,progress:t,direction:T};"enter"===n.state&&r.stepProgress(t)}function o([e]){var t=q(e.target);const o=f[t];e=e.target.offsetHeight;e!==o.height&&(o.height=e,l(o),w(o),E(o))}function a([e]){z(u);var{isIntersecting:t,target:e}=e;(t?function(e){var t=q(e);const o=f[t];e={element:e,index:t,direction:T},o.direction=T,o.state="enter",n[t]||r.stepEnter(e),v&&(n[t]=!0)}:function(e){var t=q(e);const o=f[t];o.state&&(t={element:e,index:t,direction:T},g&&("down"===T&&o.progress<1?s(e,1):"up"===T&&0{t[e].disconnect()})}function y(){f.forEach(l)}function E(e){const t=new ResizeObserver(o);t.observe(e.node),e.observers.resize=t}function w(e){var t=window.innerHeight,o=e.offset||p,n="pixels"===o.format?1:t,r=o.value*n,o=e.height/2-r,n=e.height/2-(t-r),t=`${o}px 0px ${n}px 0px`,r=d;const s=new IntersectionObserver(a,{rootMargin:t,threshold:.5,root:r});s.observe(e.node),e.observers.step=s,m&&k({id:i,step:e,marginTop:o,marginBottom:n})}function e(e){var t=window.innerHeight,o=e.offset||p,n="pixels"===o.format?1:t,n=o.value*n,n=`${-n+e.height}px 0px ${n-t}px 0px`,t=function(e,t){var o=Math.ceil(e/t);const n=[];var r=1/o;for(let e=0;e{var l;return l=a,A=0,N=0,document.addEventListener("scroll",()=>z(l)),f=([e,t=document]=[e,t],("string"==typeof e?Array.from(t.querySelectorAll(e)):e instanceof Element?[e]:e instanceof NodeList?Array.from(e):e instanceof Array?e:[]).map((e,t)=>({index:t,direction:void 0,height:e.offsetHeight,node:e,observers:{},offset:O(e.dataset.offset),top:function(e){var{top:e}=e.getBoundingClientRect();return e+window.pageYOffset-(document.body.clientTop||0)}(e),progress:0,state:void 0}))),f.length?(g=r,v=s,m=i,h=Math.max(1,+n),p=O(o),u=a,d=c,x(),f.forEach(e=>e.node.setAttribute("data-scrollama-index",e.index)),b(!0)):M("no step elements"),S},S.enable=()=>(b(!0),S),S.disable=()=>(b(!1),S),S.destroy=()=>(b(!1),x(),S),S.resize=()=>($(),S),S.offset=e=>null==e?p.value:(p=O(e),$(),S),S.onStepEnter=e=>("function"==typeof e?r.stepEnter=e:M("onStepEnter requires a function"),S),S.onStepExit=e=>("function"==typeof e?r.stepExit=e:M("onStepExit requires a function"),S),S.onStepProgress=e=>("function"==typeof e?r.stepProgress=e:M("onStepProgress requires a function"),S),S}}); 2 | -------------------------------------------------------------------------------- /docs/sticky-overlay/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Sticky Overlay Example 8 | 9 | 10 | 11 | 74 | 75 | 76 | 77 | 88 |
89 | 100 |
101 |

Sticky Overlay Example

102 |

103 | Start scrolling to see how it works. 104 |

105 |
106 | 107 |
108 |
109 |

0

110 |
111 | 112 |
113 |
114 |

STEP 1

115 |
116 |
117 |

STEP 2

118 |
119 |
120 |

STEP 3

121 |
122 |
123 |

STEP 4

124 |
125 |
126 |
127 | 128 |
129 |
130 | 131 | 132 | 133 | 196 | 197 | 198 | -------------------------------------------------------------------------------- /docs/sticky-side/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Scrollama: Sticky Side Example 8 | 9 | 10 | 11 | 80 | 81 | 82 | 83 | 94 |
95 | 106 |
107 |

Sticky Side Example

108 |

109 | Start scrolling to see how it works. 110 |

111 |
112 | 113 |
114 |
115 |
116 |

STEP 1

117 |
118 |
119 |

STEP 2

120 |
121 |
122 |

STEP 3

123 |
124 |
125 |

STEP 4

126 |
127 |
128 | 129 |
130 |

0

131 |
132 |
133 | 134 |
135 |
136 | 137 | 138 | 139 | 140 | 202 | 203 | 204 | -------------------------------------------------------------------------------- /docs/style.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | html, 6 | body { 7 | margin: 0; 8 | padding: 0; 9 | } 10 | 11 | body { 12 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, 13 | Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; 14 | min-height: 1280px; 15 | color: #3b3b3b; 16 | font-size: 24px; 17 | } 18 | 19 | p, 20 | h1, 21 | h2, 22 | h3, 23 | h4, 24 | a { 25 | margin: 0; 26 | font-weight: 400; 27 | } 28 | 29 | a, 30 | a:visited, 31 | a:hover { 32 | color: teal; 33 | text-decoration: none; 34 | border-bottom: 2px solid currentColor; 35 | } 36 | 37 | nav { 38 | display: -webkit-box; 39 | display: -ms-flexbox; 40 | display: flex; 41 | -webkit-box-align: baseline; 42 | -ms-flex-align: baseline; 43 | align-items: baseline; 44 | -webkit-box-pack: justify; 45 | -ms-flex-pack: justify; 46 | justify-content: space-between; 47 | background: #f3f3f3; 48 | padding: 1rem; 49 | padding-right: 5rem; 50 | -ms-flex-wrap: wrap; 51 | flex-wrap: wrap; 52 | } 53 | 54 | .nav__examples { 55 | display: -webkit-box; 56 | display: -ms-flexbox; 57 | display: flex; 58 | -webkit-box-align: baseline; 59 | -ms-flex-align: baseline; 60 | align-items: baseline; 61 | -ms-flex-wrap: wrap; 62 | flex-wrap: wrap; 63 | margin-top: 1rem; 64 | } 65 | 66 | .nav__examples > * { 67 | margin-right: 0.5rem; 68 | } 69 | 70 | #intro { 71 | max-width: 40rem; 72 | margin: 1rem auto; 73 | text-align: center; 74 | } 75 | 76 | .intro__hed { 77 | font-size: 2em; 78 | margin: 2rem auto 0.5rem auto; 79 | } 80 | 81 | .intro__dek { 82 | color: #8a8a8a; 83 | } 84 | 85 | .github-corner:hover .octo-arm { 86 | animation: octocat-wave 560ms ease-in-out; 87 | } 88 | 89 | @keyframes octocat-wave { 90 | 0%, 91 | 100% { 92 | transform: rotate(0); 93 | } 94 | 95 | 20%, 96 | 60% { 97 | transform: rotate(-25deg); 98 | } 99 | 100 | 40%, 101 | 80% { 102 | transform: rotate(10deg); 103 | } 104 | } 105 | 106 | @media (max-width: 500px) { 107 | .github-corner:hover .octo-arm { 108 | animation: none; 109 | } 110 | 111 | .github-corner .octo-arm { 112 | animation: octocat-wave 560ms ease-in-out; 113 | } 114 | } 115 | 116 | #intro { 117 | margin-bottom: 320px; 118 | } 119 | 120 | #outro { 121 | height: 640px; 122 | } 123 | 124 | @media (min-width: 840px) { 125 | .nav__examples { 126 | margin-top: 0; 127 | margin-left: 2rem; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export = scrollama; 2 | declare function scrollama(): scrollama.ScrollamaInstance; 3 | 4 | declare namespace scrollama { 5 | 6 | export type DecimalType = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; 7 | 8 | export type ScrollamaOptions = { 9 | step: NodeList | HTMLElement[] | string; 10 | progress?: boolean; 11 | offset?: DecimalType; 12 | threshold?: 1 | 2 | 3 | 4; 13 | order?: boolean; 14 | once?: boolean; 15 | debug?: boolean; 16 | }; 17 | 18 | export type ProgressCallbackResponse = { 19 | element: HTMLElement; 20 | index: number; 21 | progress: DecimalType; 22 | }; 23 | 24 | export type CallbackResponse = { 25 | element: HTMLElement; 26 | index: number; 27 | direction: "up" | "down"; 28 | }; 29 | 30 | export type StepCallback = (response: CallbackResponse) => void; 31 | export type StepProgressCallback = ( 32 | response: ProgressCallbackResponse 33 | ) => void; 34 | 35 | export type ScrollamaInstance = { 36 | setup: (options: ScrollamaOptions) => ScrollamaInstance; 37 | onStepEnter: (callback: StepCallback) => ScrollamaInstance; 38 | onStepExit: (callback: StepCallback) => ScrollamaInstance; 39 | onStepProgress: (callback: StepProgressCallback) => ScrollamaInstance; 40 | resize: () => ScrollamaInstance; 41 | enable: () => ScrollamaInstance; 42 | disable: () => ScrollamaInstance; 43 | destroy: () => void; 44 | offsetTrigger: (value: [number, number]) => void; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import entry from "./src/entry"; 2 | 3 | export default entry; 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scrollama", 3 | "version": "3.2.0", 4 | "description": "Lightweight scrollytelling library using IntersectionObserver", 5 | "main": "build/scrollama.js", 6 | "browser": "build/scrollama.js", 7 | "types": "index.d.ts", 8 | "scripts": { 9 | "dev": "cross-env NODE_ENV=development rollup -w -c", 10 | "build": "npm run pretest && cross-env NODE_ENV=production rollup -c && npm run docs", 11 | "pretest": "cross-env NODE_ENV=development rollup -c", 12 | "docs": "cp build/scrollama.min.js docs" 13 | }, 14 | "module": "index", 15 | "jsnext:main": "index", 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/russellsamora/scrollama.git" 19 | }, 20 | "homepage": "https://github.com/russellsamora/scrollama#readme", 21 | "keywords": [ 22 | "scrollytelling", 23 | "scroll", 24 | "scroll-driven", 25 | "step", 26 | "interactive", 27 | "graphic", 28 | "observer", 29 | "IntersectionObserver", 30 | "enter", 31 | "exit", 32 | "view", 33 | "trigger" 34 | ], 35 | "author": "Russell Samora", 36 | "license": "MIT", 37 | "devDependencies": { 38 | "cross-env": "^7.0.3", 39 | "rollup": "^1.32.1", 40 | "rollup-plugin-buble": "^0.19.8", 41 | "rollup-plugin-commonjs": "^10.1.0", 42 | "rollup-plugin-filesize": "^9.1.1", 43 | "rollup-plugin-node-resolve": "^5.2.0", 44 | "rollup-plugin-uglify": "^6.0.4" 45 | } 46 | } -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import commonjs from "rollup-plugin-commonjs"; 2 | import resolve from "rollup-plugin-node-resolve"; 3 | import { uglify } from "rollup-plugin-uglify"; 4 | import filesize from "rollup-plugin-filesize"; 5 | 6 | const isProd = process.env.NODE_ENV === "production"; 7 | 8 | const file = `build/scrollama${isProd ? ".min" : ""}.js`; 9 | 10 | const plugins = [ 11 | resolve({ 12 | jsnext: true, 13 | main: true, 14 | }), 15 | commonjs({ 16 | sourceMap: false, 17 | }), 18 | filesize(), 19 | isProd && uglify(), 20 | ]; 21 | 22 | export default { 23 | input: "index.js", 24 | output: { 25 | file, 26 | format: "umd", 27 | name: "scrollama", 28 | }, 29 | plugins, 30 | }; 31 | -------------------------------------------------------------------------------- /src/createProgressThreshold.js: -------------------------------------------------------------------------------- 1 | export default function createProgressThreshold(height, threshold) { 2 | const count = Math.ceil(height / threshold); 3 | const t = []; 4 | const ratio = 1 / count; 5 | for (let i = 0; i < count + 1; i += 1) { 6 | t.push(i * ratio); 7 | } 8 | return t; 9 | } -------------------------------------------------------------------------------- /src/debug.js: -------------------------------------------------------------------------------- 1 | 2 | // SETUP 3 | function create(className) { 4 | const el = document.createElement("div"); 5 | el.className = `scrollama__debug-step ${className}`; 6 | el.style.position = "fixed"; 7 | el.style.left = "0"; 8 | el.style.width = "100%"; 9 | el.style.zIndex = "9999"; 10 | el.style.borderTop = "2px solid black"; 11 | el.style.borderBottom = "2px solid black"; 12 | 13 | const p = document.createElement("p"); 14 | p.style.position = "absolute"; 15 | p.style.left = "0"; 16 | p.style.height = "1px"; 17 | p.style.width = "100%"; 18 | p.style.borderTop = "1px dashed black"; 19 | 20 | el.appendChild(p); 21 | document.body.appendChild(el); 22 | return el; 23 | } 24 | 25 | // UPDATE 26 | function update({ id, step, marginTop }) { 27 | const { index, height } = step; 28 | const className = `scrollama__debug-step--${id}-${index}`; 29 | let el = document.querySelector(`.${className}`); 30 | if (!el) el = create(className); 31 | 32 | el.style.top = `${marginTop * -1}px`; 33 | el.style.height = `${height}px`; 34 | el.querySelector("p").style.top = `${height / 2}px`; 35 | } 36 | 37 | export { update }; 38 | -------------------------------------------------------------------------------- /src/dom.js: -------------------------------------------------------------------------------- 1 | // DOM helper functions 2 | 3 | // public 4 | function selectAll(selector, parent = document) { 5 | if (typeof selector === 'string') { 6 | return Array.from(parent.querySelectorAll(selector)); 7 | } else if (selector instanceof Element) { 8 | return [selector]; 9 | } else if (selector instanceof NodeList) { 10 | return Array.from(selector); 11 | } else if (selector instanceof Array) { 12 | return selector; 13 | } 14 | return []; 15 | } 16 | 17 | export { selectAll }; 18 | -------------------------------------------------------------------------------- /src/entry.js: -------------------------------------------------------------------------------- 1 | import { selectAll } from "./dom"; 2 | import * as bug from "./debug"; 3 | import generateId from "./generateId"; 4 | import err from "./err"; 5 | import getIndex from "./getIndex"; 6 | import createProgressThreshold from "./createProgressThreshold"; 7 | import parseOffset from "./parseOffset"; 8 | import indexSteps from "./indexSteps"; 9 | import getOffsetTop from "./getOffsetTop"; 10 | import { setupScroll, direction, onScroll } from "./scroll"; 11 | 12 | function scrollama() { 13 | let cb = {}; 14 | 15 | let id = generateId(); 16 | let steps = []; 17 | let globalOffset; 18 | let containerElement; 19 | let rootElement; 20 | 21 | let progressThreshold = 0; 22 | 23 | let isEnabled = false; 24 | let isProgress = false; 25 | let isDebug = false; 26 | let isTriggerOnce = false; 27 | 28 | let exclude = []; 29 | 30 | /* HELPERS */ 31 | function reset() { 32 | cb = { 33 | stepEnter: () => { }, 34 | stepExit: () => { }, 35 | stepProgress: () => { }, 36 | }; 37 | exclude = []; 38 | } 39 | 40 | function handleEnable(shouldEnable) { 41 | if (shouldEnable && !isEnabled) updateObservers(); 42 | if (!shouldEnable && isEnabled) disconnectObservers(); 43 | isEnabled = shouldEnable; 44 | } 45 | 46 | /* NOTIFY CALLBACKS */ 47 | function notifyProgress(element, progress) { 48 | const index = getIndex(element); 49 | const step = steps[index]; 50 | if (progress !== undefined) step.progress = progress; 51 | const response = { element, index, progress, direction }; 52 | if (step.state === "enter") cb.stepProgress(response); 53 | } 54 | 55 | function notifyOthers(index, location) { 56 | console.log(index, location, direction, currentScrollY, previousScrollY); 57 | if (location === "above") { 58 | let i = direction === "down" ? 0 : index - 1; 59 | let end = direction === "down" ? i < index : i >= 0; 60 | let inc = direction === "down" ? 1 : -1; 61 | for (i; end; inc) { 62 | const step = steps[i]; 63 | console.log( 64 | Object.keys(step) 65 | .map((p) => `${p} - ${step[p]}`) 66 | .join("\n ") 67 | ); 68 | if (direction === "down") { 69 | if (step.state !== "enter" && step.direction !== "down") { 70 | notifyStepEnter(step.node, false); 71 | notifyStepExit(step.node, false); 72 | } else if (step.state === "enter") notifyStepExit(step.node, false); 73 | } else if (direction === "up") { 74 | if (step.state !== "enter" && step.direction === "down") { 75 | notifyStepEnter(step.node, false); 76 | notifyStepExit(step.node, false); 77 | } else if (step.state === "enter") notifyStepExit(step.node, false); 78 | } 79 | } 80 | } else if (location === "below") { 81 | for (let i = steps.length - 1; i > index; i -= 1) { 82 | const step = steps[i]; 83 | if (step.state === "enter") notifyStepExit(step.node); 84 | if (step.direction === "down") { 85 | notifyStepEnter(step.node, false); 86 | notifyStepExit(step.node, false); 87 | } 88 | } 89 | } 90 | } 91 | 92 | function notifyStepEnter(element, check = true) { 93 | const index = getIndex(element); 94 | const step = steps[index]; 95 | const response = { element, index, direction }; 96 | 97 | step.direction = direction; 98 | step.state = "enter"; 99 | 100 | // if (isPreserveOrder && check && direction !== "up") 101 | // notifyOthers(index, "above"); 102 | // if (isPreserveOrder && check && direction === "up") 103 | // notifyOthers(index, "below"); 104 | 105 | if (!exclude[index]) cb.stepEnter(response); 106 | if (isTriggerOnce) exclude[index] = true; 107 | } 108 | 109 | function notifyStepExit(element, check = true) { 110 | const index = getIndex(element); 111 | const step = steps[index]; 112 | 113 | if (!step.state) return false; 114 | 115 | const response = { element, index, direction }; 116 | 117 | if (isProgress) { 118 | if (direction === "down" && step.progress < 1) notifyProgress(element, 1); 119 | else if (direction === "up" && step.progress > 0) 120 | notifyProgress(element, 0); 121 | } 122 | 123 | step.direction = direction; 124 | step.state = "exit"; 125 | 126 | cb.stepExit(response); 127 | } 128 | 129 | /* OBSERVERS - HANDLING */ 130 | function resizeStep([entry]) { 131 | const index = getIndex(entry.target); 132 | const step = steps[index]; 133 | const h = entry.target.offsetHeight; 134 | if (h !== step.height) { 135 | step.height = h; 136 | disconnectObserver(step); 137 | updateStepObserver(step); 138 | updateResizeObserver(step); 139 | } 140 | } 141 | 142 | function intersectStep([entry]) { 143 | onScroll(containerElement); 144 | 145 | const { isIntersecting, target } = entry; 146 | if (isIntersecting) notifyStepEnter(target); 147 | else notifyStepExit(target); 148 | } 149 | 150 | function intersectProgress([entry]) { 151 | const index = getIndex(entry.target); 152 | const step = steps[index]; 153 | const { isIntersecting, intersectionRatio, target } = entry; 154 | if (isIntersecting && step.state === "enter") 155 | notifyProgress(target, intersectionRatio); 156 | } 157 | 158 | /* OBSERVERS - CREATION */ 159 | function disconnectObserver({ observers }) { 160 | Object.keys(observers).map((name) => { 161 | observers[name].disconnect(); 162 | }); 163 | } 164 | 165 | function disconnectObservers() { 166 | steps.forEach(disconnectObserver); 167 | } 168 | 169 | function updateResizeObserver(step) { 170 | const observer = new ResizeObserver(resizeStep); 171 | observer.observe(step.node); 172 | step.observers.resize = observer; 173 | } 174 | 175 | function updateResizeObservers() { 176 | steps.forEach(updateResizeObserver); 177 | } 178 | 179 | function updateStepObserver(step) { 180 | const h = window.innerHeight; 181 | const off = step.offset || globalOffset; 182 | const factor = off.format === "pixels" ? 1 : h; 183 | const offset = off.value * factor; 184 | const marginTop = step.height / 2 - offset; 185 | const marginBottom = step.height / 2 - (h - offset); 186 | const rootMargin = `${marginTop}px 0px ${marginBottom}px 0px`; 187 | const root = rootElement; 188 | 189 | const threshold = 0.5; 190 | const options = { rootMargin, threshold, root }; 191 | const observer = new IntersectionObserver(intersectStep, options); 192 | 193 | observer.observe(step.node); 194 | step.observers.step = observer; 195 | 196 | if (isDebug) bug.update({ id, step, marginTop, marginBottom }); 197 | } 198 | 199 | function updateStepObservers() { 200 | steps.forEach(updateStepObserver); 201 | } 202 | 203 | function updateProgressObserver(step) { 204 | const h = window.innerHeight; 205 | const off = step.offset || globalOffset; 206 | const factor = off.format === "pixels" ? 1 : h; 207 | const offset = off.value * factor; 208 | const marginTop = -offset + step.height; 209 | const marginBottom = offset - h; 210 | const rootMargin = `${marginTop}px 0px ${marginBottom}px 0px`; 211 | 212 | const threshold = createProgressThreshold(step.height, progressThreshold); 213 | const options = { rootMargin, threshold }; 214 | const observer = new IntersectionObserver(intersectProgress, options); 215 | 216 | observer.observe(step.node); 217 | step.observers.progress = observer; 218 | } 219 | 220 | function updateProgressObservers() { 221 | steps.forEach(updateProgressObserver); 222 | } 223 | 224 | function updateObservers() { 225 | disconnectObservers(); 226 | updateResizeObservers(); 227 | updateStepObservers(); 228 | if (isProgress) updateProgressObservers(); 229 | } 230 | 231 | /* SETUP */ 232 | const S = {}; 233 | 234 | S.setup = ({ 235 | step, 236 | parent, 237 | offset = 0.5, 238 | threshold = 4, 239 | progress = false, 240 | once = false, 241 | debug = false, 242 | container = undefined, 243 | root = null 244 | }) => { 245 | 246 | setupScroll(container); 247 | 248 | steps = selectAll(step, parent).map((node, index) => ({ 249 | index, 250 | direction: undefined, 251 | height: node.offsetHeight, 252 | node, 253 | observers: {}, 254 | offset: parseOffset(node.dataset.offset), 255 | top: getOffsetTop(node), 256 | progress: 0, 257 | state: undefined, 258 | })); 259 | 260 | if (!steps.length) { 261 | err("no step elements"); 262 | return S; 263 | } 264 | 265 | isProgress = progress; 266 | isTriggerOnce = once; 267 | isDebug = debug; 268 | progressThreshold = Math.max(1, +threshold); 269 | globalOffset = parseOffset(offset); 270 | containerElement = container; 271 | rootElement = root; 272 | 273 | reset(); 274 | indexSteps(steps); 275 | handleEnable(true); 276 | return S; 277 | }; 278 | 279 | S.enable = () => { 280 | handleEnable(true); 281 | return S; 282 | }; 283 | 284 | S.disable = () => { 285 | handleEnable(false); 286 | return S; 287 | }; 288 | 289 | S.destroy = () => { 290 | handleEnable(false); 291 | reset(); 292 | return S; 293 | }; 294 | 295 | S.resize = () => { 296 | updateObservers(); 297 | return S; 298 | }; 299 | 300 | S.offset = (x) => { 301 | if (x === null || x === undefined) return globalOffset.value; 302 | globalOffset = parseOffset(x); 303 | updateObservers(); 304 | return S; 305 | }; 306 | 307 | S.onStepEnter = (f) => { 308 | if (typeof f === "function") cb.stepEnter = f; 309 | else err("onStepEnter requires a function"); 310 | return S; 311 | }; 312 | 313 | S.onStepExit = (f) => { 314 | if (typeof f === "function") cb.stepExit = f; 315 | else err("onStepExit requires a function"); 316 | return S; 317 | }; 318 | 319 | S.onStepProgress = (f) => { 320 | if (typeof f === "function") cb.stepProgress = f; 321 | else err("onStepProgress requires a function"); 322 | return S; 323 | }; 324 | return S; 325 | } 326 | 327 | export default scrollama; 328 | -------------------------------------------------------------------------------- /src/err.js: -------------------------------------------------------------------------------- 1 | export default function err(msg) { 2 | console.error(`scrollama error: ${msg}`); 3 | } -------------------------------------------------------------------------------- /src/generateId.js: -------------------------------------------------------------------------------- 1 | export default function generateId() { 2 | const alphabet = "abcdefghijklmnopqrstuvwxyz"; 3 | const date = Date.now(); 4 | const result = []; 5 | for (let i = 0; i < 6; i += 1) { 6 | const char = alphabet[Math.floor(Math.random() * alphabet.length)]; 7 | result.push(char); 8 | } 9 | return `${result.join("")}${date}`; 10 | } -------------------------------------------------------------------------------- /src/getIndex.js: -------------------------------------------------------------------------------- 1 | export default function getIndex(node) { 2 | return +node.getAttribute("data-scrollama-index"); 3 | } 4 | -------------------------------------------------------------------------------- /src/getOffsetTop.js: -------------------------------------------------------------------------------- 1 | export default function getOffsetTop(node) { 2 | const { top } = node.getBoundingClientRect(); 3 | const scrollTop = window.pageYOffset; 4 | const clientTop = document.body.clientTop || 0; 5 | return top + scrollTop - clientTop; 6 | } 7 | -------------------------------------------------------------------------------- /src/indexSteps.js: -------------------------------------------------------------------------------- 1 | export default function indexSteps(steps) { 2 | steps.forEach((step) => 3 | step.node.setAttribute("data-scrollama-index", step.index) 4 | ); 5 | } -------------------------------------------------------------------------------- /src/parseOffset.js: -------------------------------------------------------------------------------- 1 | export default function parseOffset(x) { 2 | if (typeof x === "string" && x.indexOf("px") > 0) { 3 | const v = +x.replace("px", ""); 4 | if (!isNaN(v)) return { format: "pixels", value: v }; 5 | else { 6 | err("offset value must be in 'px' format. Fallback to 0.5."); 7 | return { format: "percent", value: 0.5 }; 8 | } 9 | } else if (typeof x === "number" || !isNaN(+x)) { 10 | if (x > 1) err("offset value is greater than 1. Fallback to 1."); 11 | if (x < 0) err("offset value is lower than 0. Fallback to 0."); 12 | return { format: "percent", value: Math.min(Math.max(0, x), 1) }; 13 | } 14 | return null; 15 | } -------------------------------------------------------------------------------- /src/scroll.js: -------------------------------------------------------------------------------- 1 | let previousScrollY; 2 | let currentScrollY; 3 | let comparisonScrollY; 4 | let direction; 5 | 6 | function onScroll(container) { 7 | const scrollTop = container ? container.scrollTop : window.pageYOffset; 8 | 9 | if (currentScrollY === scrollTop) return; 10 | 11 | previousScrollY = currentScrollY; 12 | currentScrollY = scrollTop; 13 | if (currentScrollY > comparisonScrollY) direction = "down"; 14 | else if (currentScrollY < comparisonScrollY) direction = "up"; 15 | comparisonScrollY = currentScrollY; 16 | } 17 | 18 | function setupScroll(container) { 19 | previousScrollY = 0; 20 | currentScrollY = 0; 21 | comparisonScrollY = 0; 22 | document.addEventListener("scroll", () => onScroll(container)); 23 | } 24 | 25 | export { setupScroll, onScroll, direction, previousScrollY, currentScrollY }; 26 | --------------------------------------------------------------------------------