Parallax scrolling is an effect used to create the illusion of depth by having several layers moving at different speeds.
In this article, we'll see how to implement a simple Vertical Parallax Scrolling.
You are free to copy, modify and use this code as you wish.
This effect is quite heavy on mobile devices, and very few will reach a decent framerate, especially if you're using several layers with transparencies and/or CSS effects, so it is important that you provide a "flat" fallback for mobile users.
This is not a limitation of the solution proposed here: many big libraries exist that implement parallax, but at the moment I'm writing this, they all suck on mobile devices.
We want to define some "Parallax areas", which are containers for several layers. Since the layers have to move inside their areas, the size of the areas cannot be automatically calculated and must be expressed with inline CSS.
Layers will have a depth property (I'll call this data-parallax), which can change in time.
Inside the areas, vertical offset will be applied to the layers using the top property.
Let's see the code to run for each frame to move the layers around:
Smooth scrolling is necessary for 2 reasons: first, it makes the Parallax effect much more visible, and second, it hides the lag when the browser is not running at a perfect 60 fps.
You can use a library for smooth scrolling, or see my article about it.
I'll be using my lightweight smooth scrolling. I'll apply it to the whole page and use it to run the parallax code perfectly synced with the scrolling:
First, we need to load the parallax and the smooth scrolling. I'll assume you're using my smooth scroll implementation, but you can use another library if you prefer.
Now we can define a px_area and put stuff into it
The data-parallax attribute indicates the depth of the element.
-1 means it's fixed to the background Values between -1 and 0 indicate the depth
0 means it scrolls with the page
Values between above 0 indicate how much it sticks out
Note that I have sorted the layers by increasing depth. That is because the z-index is not touched, allowing for background elements to be drawn in front of the foreground if you want to make your eyes bleed.
Let's see an example with a few layers.
Notice the depth effect as you scroll the page.