From 253a70f91a0c1adac72cabd0c553c4e5c63b71b3 Mon Sep 17 00:00:00 2001 From: Daniel Kurowski <daniel.kurowski@grifart.cz> Date: Mon, 8 Jun 2020 09:35:22 +0200 Subject: [PATCH] Added scrollToOffset() method --- src/scrollers/scrollToOffset.ts | 19 ++++++++ src/scrollers/scrollToOffset.unitTest.html | 52 ++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 src/scrollers/scrollToOffset.ts create mode 100644 src/scrollers/scrollToOffset.unitTest.html diff --git a/src/scrollers/scrollToOffset.ts b/src/scrollers/scrollToOffset.ts new file mode 100644 index 0000000..e90bab5 --- /dev/null +++ b/src/scrollers/scrollToOffset.ts @@ -0,0 +1,19 @@ +import * as Velocity from 'velocity-animate'; +import {EASE_IN_SKIP_OUT_EASING} from '../easing/setupVelocity'; + +export function scrollToOffset( + topOffset: number, + onScrollFinishedCallback?: () => void, +): void +{ + /** + * Setting `<html>` as the element to scroll to with offset simulates `window.scrollTo()` behavior. + * See last paragraph at http://velocityjs.org/#scroll + */ + Velocity.animate(document.documentElement, 'scroll', { + duration: 1200, // todo: different depending on offset from page top? + offset: topOffset, + easing: EASE_IN_SKIP_OUT_EASING, + complete: onScrollFinishedCallback, + }); +} diff --git a/src/scrollers/scrollToOffset.unitTest.html b/src/scrollers/scrollToOffset.unitTest.html new file mode 100644 index 0000000..a27fc80 --- /dev/null +++ b/src/scrollers/scrollToOffset.unitTest.html @@ -0,0 +1,52 @@ +<!doctype html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>scrollToOffset() scroll test</title> + <script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5/velocity.min.js"></script> + <script src="../../dist/index.js"></script> + <script> + SmoothScroll.enable({ + scrollOnLoad: false, + scrollOnLinkClick: false, + }); + </script> + <style type="text/css"> + body { + margin: 0 auto; + max-width: 40rem; + } + + .target { + position: absolute; + top: 5000px; + padding-bottom: 200vh; /* make some space so that scrolling target can reach top of viewport */ + } + </style> +</head> +<body> + +<div> + <p> + <strong>Click button below. View should scroll down.</strong> + </p> + <button type="button" id="triggerer">â–¶ Run test</button> + <script> + document.getElementById('triggerer').addEventListener('click', () => + SmoothScroll.scrollToOffset( + 5000, + () => document.getElementById('greenText').style.color = 'green', + ) + ); + </script> + + <div class="target"> + <h1>Target on <code>SmootScroll.scrollToOffset()</code> call</h1> + <p> + <strong>If view was scrolled smoothly to heading above, you see it complete and <span id="greenText">this text is green</span>, the test is passing. âś”</strong> + </p> + </div> +</div> +</body> +</html> -- GitLab