├── .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 |
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 | [](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 |
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 |