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

Pete FowlerPete Fowler
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
0
Subscribe to my newsletter

Read articles from Pete Fowler directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pete Fowler
Pete Fowler

Full stack software engineer building a financial data integration SaaS product. Led a complete rebuild of the team’s web app using JavaScript, TypeScript, React, C#/.NET, EntityFramework Core and SQL, with testing in Jest, React Testing Library, xUnit, and Moq. Utilized AWS services including MySQL RDS, EC2, ECS with Docker, S3, Lambda, and EventBridge. Passionate about continuous improvement, clean code, and best practices (where they exist). Dedicated rock climber and runner based in Colorado. Names variables like a first born child.