This is what we want.
Whenever we want to change style or play with the HTML elements (add elements, animate elements) on scroll, the scrollTop property comes handy. We can scroll the content inside a div or the whole body using scrollTop property.
We are going to use the same scrollTop property to do the same. We are also going to use CSS to animate the image.
Which will just add basic HTML elements with some texts and an image like this:
Let’s style the texts a bit with Google fonts so it looks nice. Also, let’s hide the image initially with CSS visibility:hidden property. You can style the image as per your requirements.
We have added the animation in CSS for which we will add the @keyframes at the end.
Now, let’s add this CSS class which will be used to display the image on scroll.
We are going to create a function and call it on a window.onscroll event. Let’s look at the function first.
In the function above, we are checking the distance from top using scrollTop. We don’t have much content so we are just checking if it’s greater than 100px. You can adjust it using your requirements.
We are check both the document.body(for Safari) and document.documentElement(for other browsers). If the condition matches then we’ll simply add the class we created in CSS.
This will do the trick. Well, mostly. We still need to add animation.
Let’s add the @keyframes for the animation we added earlier.
The animation makes the display of image really smooth.
animation display image scroll scrollTop