Created
October 17, 2020 17:47
-
-
Save LiamChapman/e0773a358ae0210cf06331a0b8b7e47a to your computer and use it in GitHub Desktop.
Interpolate values on scroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://www.trysmudford.com/blog/linear-interpolation/ | |
| // ^ fantastic guide from here!! | |
| const lerp = (x, y, a) => x * (1 - a) + y * a; | |
| const invlerp = (a, b, v) => clamp((v - a) / (b - a)) | |
| const clamp = (v, min = 0, max = 1) => Math.min(max, Math.max(min, v)); | |
| const items = [{ | |
| scrollStart: 70, // Scroll tracking start point | |
| scrollEnd: 120, // Scroll tracking end point | |
| property: '--css-variable-property', // CSS Custom property | |
| from: 1, // CSS property lower limit | |
| to: 0.5, // CSS property upper limit | |
| value: 0 // Starting point | |
| suffix: null // Optional suffix (px, deg, turn) | |
| }]; | |
| // in css use something like: | |
| // height: var(--css-variable-property); | |
| const scroll = (e) => { | |
| items.forEach(item => { | |
| const n = invlerp(item.scrollStart, item.scrollEnd, window.scrollY); // or e.target.scrollTop ..etc | |
| if (item.value !== n) { | |
| item.value = n; | |
| window.requestAnimationFrame(() => { | |
| const property = lerp(item.from, item.to, n); | |
| document.documentElement.style.setProperty(item.property, property + (item.suffix || null)) | |
| }) | |
| } | |
| }); | |
| }; | |
| window.addEventListener('scroll', scroll); | |
| scroll(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment