Created
November 15, 2018 00:12
-
-
Save tomasdev/6a347587cdc7b73c7e3c329b9a0fdb75 to your computer and use it in GitHub Desktop.
Utilities for easing and animation ala jquery but vanilla javascript
This file contains 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
// easing equations from https://github.com/danro/easing-js/blob/master/easing.js | |
export const EASING = { | |
linear: x => x, | |
easeOut: x => Math.sin(x * (Math.PI / 2)), | |
easeInOut: x => (-0.5 * (Math.cos(Math.PI * x) - 1)), | |
easeInOutQuint: x => (x /= 0.5) < 1 ? 0.5 * Math.pow(x, 5) : 0.5 * (Math.pow((x - 2), 5) + 2) | |
}; | |
export const animate = (method, ms = 1000, ease = EASING.easeInOut) => { | |
const now = () => (window.performance || Date).now(); | |
const startTime = now(); | |
const step = () => { | |
let time = (now() - startTime); | |
time = time > ms ? ms : time; | |
method(ease(time / ms)); | |
if (time < ms) { | |
requestAnimationFrame(step); | |
} | |
}; | |
requestAnimationFrame(step); | |
}; | |
export const scrollToElement = ({ element, offset = 0, ms, ease }) => { | |
const navHeight = document.querySelector('.uebp-header-sticky').offsetHeight; | |
const baseY = window.scrollY; | |
const difference = element.offsetTop - offset - navHeight - baseY; | |
animate(x => scrollTo(0, baseY + difference * x), ms, ease); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment