Skip to content

Instantly share code, notes, and snippets.

@trevorblades
Created September 11, 2017 18:56
Show Gist options
  • Save trevorblades/156f1e302cb70d77feed6acf11c6e72c to your computer and use it in GitHub Desktop.
Save trevorblades/156f1e302cb70d77feed6acf11c6e72c to your computer and use it in GitHub Desktop.
Scroll animation
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- | --- 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