Handling Scroll Based Animation in React / Animate Image zoom-in on scroll up and zoom-out on scroll down

blazer road
2 min readFeb 24, 2021

--

In this story I will show you how easy it is to apply simple cool animation in React.

What we want to is to apply animation to our image to be zoom-in when we scroll up and zoom-out when we scroll down something like this gif:

To do this, we need to know that we are scrolling up or down :

First, we use this line to add listener to call the “onScroll” function for each change in scroll.

window.addEventListener("scroll", onScroll);

To find out if the scrolling direction is up or down, we save the previous scroll value in the “preScroll” variable and compare it with the new value in every scroll change. So when the value of this condition

preScroll.current > window.scrollY

is true, it means we scroll down and otherwise up.

Now is the time to add our animation to the image for that we need to add this style to our image

style={{          
transition: "transform 1000ms ease-in-out",
transform: `scale(${scale})`
}}

By changing the scale according to the scroll status, we can add animation to the image.

There is only one small problem, and that is that we want the image to be zoom-in when it appears on the screen and zoom-out when it is leaving .

For that, we need to know the position of the image on the screen. this code solves this problem for us:

const botPos = (element) => element.getBoundingClientRect().bottom;

This calculate the distance of the bottom of the Image from the top of the screen so when

divBotPos > window.innerHeight

that mean our image is leaving the screen and otherwise it is on the screen.

In the end it will look like this:

You can also see a DEMO at the link below:

https://codesandbox.io/s/inspiring-tharp-geyf1?file=/src/App.js

--

--

blazer road

full stack developer with NODEJS & c# and react/react native