A few weeks ago, I saw Kevin Powell’s video about scroll animations, and it blew my mind!
It’s because making scroll animation effects used to be quite a complicated CSS technique, but with the CSS value functions he introduced, such as view() and scroll(), it seems to make it so easy!
So, I gave it a try right away, and honestly, it wasn’t as easy as I expected. It’s because implementing the precise values of animation-timeline
and animation-range
was quite challenging.
Nevertheless, the most benefit of using these was I could make scroll animations using CSS only.
Some of the code snippets were like this.
Also, the result was great!
However, there was a big problem. As for now, these functions are experimental and have very limited browser supports.
I could see the animation on the Chrome web browser but did work on firefox and safari at all.🙁
For that reason, I decided to make the scroll hook to make the same animation effects.
To make this work, I tried to make the logic as simple as possible.
My goal was like this.
- When the designated target reaches the specified scroll starting position, the animation begins. The animation ends when the target arrives at the designated scroll ending position.
- With this hook, I should get the transition values on the scroll position.
To make this happen, I needed these parameters
- Assign animating target
- Set initial values. Since we sometimes need several transition values such as transitionY, scroll, and opacity, get the initial values as a number array. The ending values are always 0
- Animation boundary. Options for deciding animation boundary to window or target
- Threshold. threshold for triggering animation in the boundary. Since it’s about vertical scrolling, it’s only related the vertical position.
And, here is the code for the initial setups
Then, make the function to update the transition values depending on the scroll position.
Get the current scroll position and within the looping function, calculate the scroll position of each target item and the height of the target item.
Next, calculate the start and end values of scroll position.
By adding the window’s scroll position and the item's top position, and then subtracting the viewport height, the scroll position at which the transition should start can be determined.
Then, calculate the transition values based on the scroll position
Add the function into the event listener in the useEffect.
As a result, the same effect to using scroll() and view() CSS properties was implemented.✨