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

## Depth and interactivity
Well done parallax scrolling effects can add incredible depth and interactivity to a web page. This simple example uses a [fixed](https://developer.mozilla.org/en-US/docs/Web/CSS/position) 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1660498434892/qLoUh3LXl.gif align="left")
[Link to site](https://petefowler.dev/)

## Implementation
This works by stacking the fixed background image underneath the other elements by using a lower [z-index](https://developer.mozilla.org/en-US/docs/Web/CSS/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](https://developer.mozilla.org/en-US/docs/Web/CSS/top)

## Links 
- [Simple parallax example with instructions](https://dev.to/javascriptacademy/create-parallax-scrolling-effect-with-vanilla-javascript-5b4h)
- [Parallax scroll effect best practices with some incredible examples](https://xd.adobe.com/ideas/principles/web-design/best-practices-for-parallax-websites/)
- [The Boat - an amazing, immersive, storytelling experience for inspiration](https://www.sbs.com.au/theboat/)


