Created
September 11, 2017 18:56
-
-
Save trevorblades/156f1e302cb70d77feed6acf11c6e72c to your computer and use it in GitHub Desktop.
Scroll animation
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
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | --- 0% | |
- | | |
- | | |
- | --- 50% | |
- | | |
- | | |
- | --- 100% | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
- | |
const IMAGE_EXPAND_AMOUNT = 40; | |
const IMAGE_SCROLL_THRESHOLD = 120; // number of pixels surrounding the image where animation becomes active | |
onScroll() { | |
const scrollTop = window.scrollTop; | |
const imageScrollTop = this.image.offsetY; | |
const imageAnimateStart = imageScrollTop - IMAGE_SCROLL_THRESHOLD; | |
const imageAnimateEnd = imageScrollTop + IMAGE_SCROLL_THRESHOLD; | |
if (scrollTop >= imageAnimateStart || scrollTop <= imageAnimateEnd) { | |
// we should be animating | |
const animatableAreaScrolled = scrollTop - imageAnimateStart; | |
const totalAnimatableArea = imageAnimateEnd - imageAnimateStart; | |
const percentAnimated = animatableAreaScrolled / totalAnimatableArea; | |
return this.setState({percentAnimated}); | |
} | |
return this.setState({percentAnimated: scrollTop > imageAnimateEnd ? 1 : 0}); | |
} | |
render() { | |
return ( | |
<div> | |
<div | |
ref={node => { | |
this.image = node; | |
}} | |
> | |
<img style={{transform: `translateY(${IMAGE_EXPAND_AMOUNT * -1 * percentAnimated}px)`}} /> | |
<img /> | |
<img style={{top: IMAGE_EXPAND_AMOUNT * percentAnimated}} /> | |
</div> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment