Skip to content
Snippets Groups Projects
Commit 253a70f9 authored by Daniel Kurowski's avatar Daniel Kurowski
Browse files

Added scrollToOffset() method

parent 80fc53d7
No related branches found
No related tags found
1 merge request!8Resolve "Expose manual scrollTo*() methods to public API"
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,
});
}
<!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>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment