Pete Fowler
blog.petefowler.dev

blog.petefowler.dev

How to create a parallax scroll effect using vanilla JavaScript and CSS

How to create a parallax scroll effect using vanilla JavaScript and CSS

Pete Fowler's photo
Pete Fowler
·Aug 14, 2022·

2 min read

Depth and interactivity

Well done parallax scrolling effects can add incredible depth and interactivity to a web page. This simple example uses a fixed background image. The site content is stacked on top and scrolling over it, while transparent <div> elements reveal the background. The background moves at 40% of the window scroll speed.

parallaxSmall.gif Link to site

Implementation

This works by stacking the fixed background image underneath the other elements by using a lower z-index. The revealing <div> elements act as a transparent window by using the opacity: 0; CSS property.

The parallax scroll effect of the background image is done with the following JavaScript:

const background = document.querySelector('#background');

const parallax = () => {
  const { scrollY } = window;
  background.style.top = (scrollY * -.4) + 'px';
}
window.addEventListener('scroll', parallax);

The code above is

  • Getting the background element
  • Attaching a scroll event listener to the window
  • Every time the window is scrolled, the callback function gets the position the user has scrolled down vertically in pixels from window.scrollY
  • It then moves the background image .4x the distance the window was scrolled by editing the CSS top property
 
Share this