Skip to content

Instantly share code, notes, and snippets.

@iamravenous
Last active October 30, 2019 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamravenous/7cfabf0e1de8cda14daf44f6a53a90a3 to your computer and use it in GitHub Desktop.
Save iamravenous/7cfabf0e1de8cda14daf44f6a53a90a3 to your computer and use it in GitHub Desktop.
Micro library to animate elements with CSS based on scroll position
/*
* Nifty Animate
* Micro library to animate elements with CSS based on scroll position
* Requires: Lodash throttle & debounce
* Author: Franco Moya - @iamravenous
* Version: 1.1 Beta
*/
const offset = el => {
const rect = el.getBoundingClientRect();
return {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX
};
};
const niftyAnimate = () => {
let animatedElements = document.querySelectorAll("[data-animate]");
let scrollPos = window.pageYOffset;
let windowHeight = window.innerHeight;
let windowBottomPos = scrollPos + windowHeight;
animatedElements.forEach(el => {
const elementHeight = el.offsetHeight;
const elementTopPos = offset(el).top;
const elementBottomPos = elementTopPos + elementHeight;
if (elementBottomPos >= scrollPos && elementTopPos <= windowBottomPos) {
el.setAttribute("data-animate", "true");
}
});
};
niftyAnimate();
window.addEventListener(
"resize",
_.debounce(niftyAnimate, 50, true));
window.addEventListener(
"orientationchange",
_.debounce(niftyAnimate, 50, true)
);
window.addEventListener(
"scroll",
_.throttle(function() {
niftyAnimate();
}, 99)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment