Last active
October 30, 2019 00:42
-
-
Save iamravenous/7cfabf0e1de8cda14daf44f6a53a90a3 to your computer and use it in GitHub Desktop.
Micro library to animate elements with CSS based on scroll position
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
/* | |
* 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