Skip to content

Instantly share code, notes, and snippets.

@tomasdev
Created November 15, 2018 00:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasdev/6a347587cdc7b73c7e3c329b9a0fdb75 to your computer and use it in GitHub Desktop.
Save tomasdev/6a347587cdc7b73c7e3c329b9a0fdb75 to your computer and use it in GitHub Desktop.
Utilities for easing and animation ala jquery but vanilla javascript
// 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