By Luis Manuel
There is a kind of animation that has not stopped increasing its presence in the most modern and original websites: the animations based on the scroll
event of JavaScript. This trend literally exploded when the parallax effects appeared, and since then its use has become more frequent.
But the truth is that you must be very careful when implementing an animation based on scroll, since it can seriously affect the performance of the website, especially on mobile devices.
That’s why we invite you to continue reading the tutorial, where we will implement from scratch and with vanilla JavaScript, this beautiful animation based on scroll, also keeping good performance even on mobile devices:
Let’s start!
This tutorial uses Sass to loop through 10 images with @for
and reference parent selectors with Parent Selector (&
). It is possible to accomplish the same result with CSS, but it will require additional work.
We will use a simple HTML structure, where each image in the design will actually be a div
element in the HTML code, and the images will be defined and positioned with CSS, which will facilitate this task:
Now let’s look at the CSS styles needed to achieve the desired design.
First, let’s start by creating the layout.
This time we will use a CSS Grid, taking advantage of the fact that this technology is already supported in all modern browsers.
It is important to note that, in addition to the CSS grid, we are giving the .container
element a fixed
position. This will make this element not affected by the default scroll behavior, allowing to perform custom transforms with JavaScript.
Now let’s see how to define the styles associated with the images. See the comments for a brief explanation of each part:
Now let’s make some adjustments for small screens since there we should have a column instead of two.
And this way we have our design almost ready, we just need to add the background to the body, which we will not explain so as not to extend the tutorial with trivial details.
Note also that for now, you will not be able to scroll, since we have given a fixed position to the container element. Next, we will solve this problem and bring our design to life.
Now let’s see how to implement, from scratch and using vanilla JavaScript, a custom scroll movement, smoother and suitable for the animations planned. All this we will achieve without trying to reimplement all the work associated with the scroll that the web browser does. Instead, we will keep the native scroll functionality, at the same time that we will have a custom scroll behavior. Sounds good, huh? Let’s see how to do it!
First let’s look at some useful functions that we will be using. Lean on the comments for a better understanding:
And these are the variables that we will be using also, described briefly to understand much better the code that we will present below:
With all this ready, let’s see how to implement our custom scroll behavior.
To make our webpage scrollable, we will add a new div
element to the body
dynamically, to which we will set the same height
of our container element, in such a way that the scrollable area will be the same.
We also need a bit of CSS styles so that our .fake-scroll
element makes the page scrollable, without interfering with the layout and the other elements:
Now let’s see the function responsible for calculating all the necessary dimensions, and preparing the ground for the animations:
Once the setupAnimation
function is called, the page will be scrollable, and everything will be ready to start listening to the scroll
event and run the animation.
So let’s see what we will do when the scroll
event is triggered:
Each time the scroll
event is triggered, you simply update the target variable with the new position, and call the startAnimation
function, which does nothing but start the animation if it is not active yet. Here is the code:
Now let’s see the internal behavior for the updateAnimation
function, which is the one that actually performs all calculations and transformations in each frame, to achieve the desired animation.
Please follow the comments for a better understanding of the code:
And our custom scroll behavior is ready!
After calling the function setupAnimation
, you could scroll as you normally would, and the .container
element would be moved in correspondence, but with a very smooth and pleasant effect.
Then we only have to animate the images in correspondence with the position in which they are with respect to the viewport. Let’s see how to do it!
To animate the images we will use the current position of the fake scroll (current
), and we will calculate the intersectionRatio
(similar to the value from the IntersectionObserver API
) between each image and the viewport. Then, we just have to apply the transformations that we want depending on that ratio, and we will obtain the desired animation.
The idea is to show the image without any transformation when it is in the center of the screen (intersectionRatio = 1
), and to increase the transformations as the image moves towards the ends of the screen (intersectionRatio = 0
).
Pay close attention to the code shown below, especially the part where the intersectionRatio
for each image is calculated. This value is essential to then apply the appropriate CSS transformations. Please follow the comments for a better understanding:
And we are almost ready to enjoy our animation. We only need to make the initial call to the setupAnimation
function, in addition to updating the dimensions in case the resize
event is triggered:
Scroll! Scroll! Scroll!
So far, everything should work perfectly on the desktop, but the story is very different if we try the animation on mobile devices.
The problem occurs when the address bar (and the navigation bar in the footer of some browsers) hides when it is scrolled down and is shown again when scrolling upwards. This is not a bug, but a feature. The problem appears when we use the CSS unit vh
, since in this process that unit is recalculated, resulting in an unwanted jump in our animation.
The workaround that we have implemented is to use the small library vh-fix
, which defines, for each element with the class .vh-fix
, a static height
based on their vh
value and the viewport height
.
In this way, we should no longer have unwanted jumps.
And we have finished implementing this beautiful scroll-based animation.
You can check the live demo, play with the code in Codepen, or check the full code in the repository in Github.
Please keep in mind that the objective of this tutorial is essentially academic and to be used as inspiration. To use this demo in production other aspects must be taken into account, such as accessibility, browser support, the use of some debounce
function for the scroll
and resize
events, etc.
Without further ado, we hope you enjoyed it and it has been useful!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!